-
Notifications
You must be signed in to change notification settings - Fork 1
/
226. Invert Binary Tree
64 lines (51 loc) · 1.17 KB
/
226. Invert Binary Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
题目描述:
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
题目思路:
上面的max howell碰见的事有点意思,特意搜了搜。
这个题让交换左右子数,存一个变量temp,用来交换就ok
时间复杂度O(n)
答案详解:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void convert(TreeNode* root)
{
if(root)
{
struct TreeNode* p =root;
p = root->left;
root->left = root->right;
root->right = p;
convert(root->left);
convert(root->right);
}
}
TreeNode* invertTree(TreeNode* root) {
if(root==NULL)
return NULL;
convert(root);
return root;
}
};