Easy-20

xiaoxiao2021-02-27  642

leetcode   226. Invert Binary Tree

Invert a binary tree.

4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1

AC;

/**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     struct TreeNode *left;  *     struct TreeNode *right;  * };  */ struct TreeNode* invertTree(struct TreeNode* root) {     if(root==NULL){         return ;     }     struct TreeNode* node;     if(root->left!=NULL){         invertTree(root->left);     }     if(root->right!=NULL){         invertTree(root->right);     }     node=root->left;     root->left=root->right;     root->right=node;     return root; }

tips:开始准备想着遍历把值取出来,然后逆序,再遍历放回去。后来又发现只要遍历一次,遍历过程中交换左右子树即可。想出这个方法,对于菜鸟的我来说,很激动!~

转载请注明原文地址: https://www.6miu.com/read-530.html

最新回复(0)