226. Invert Binary Tree

时间:2021-02-04 11:44:27   收藏:0   阅读:0

仅供自己学习

 

题目:

Invert a binary tree.

Example:

Input:

4
/ \
2 7
/ \ / \
1 3 6 9
Output:

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

 

思路:

这就是直接交换数据就可以了,可以前序遍历,后序遍历,中序遍历的交换

代码:

前序遍历:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     TreeNode* invertTree(TreeNode* root) {
15         if(root == NULL) return NULL;
16         TreeNode* temp;
17         temp=root->left;
18         root->left =root->right;
19         root->right = temp;
20         
21         invertTree(root->left);
22         invertTree(root->right);
23         return root;
24     }
25 };

 

中序遍历:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     TreeNode* invertTree(TreeNode* root) {
15         if(root == NULL) return NULL;
16         TreeNode* temp;
17         invertTree(root->left);
18         temp=root->left;
19         root->left =root->right;
20         root->right = temp;
21         
22         invertTree(root->left);
23         
24         return root;
25     }
26 };

 

后序遍历:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     TreeNode* invertTree(TreeNode* root) {
15         if(root == NULL) return NULL;
16         TreeNode* temp;
17         invertTree(root->left);
18         invertTree(root->right);
19         temp=root->left;
20         root->left =root->right;
21         root->right = temp;
22         
23         
24         return root;
25     }
26 };

 

在leetcode跑,后序遍历时间消耗最佳,前序和中序差别不大

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!