-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path226.InvertBinaryTree.h
More file actions
65 lines (52 loc) · 1.25 KB
/
226.InvertBinaryTree.h
File metadata and controls
65 lines (52 loc) · 1.25 KB
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
65
/*
2015-06-13
bluepp
May the force be with me!
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
https://leetcode.com/problems/invert-binary-tree/
*/
/* recursion, 2015-07-20 update */
TreeNode* invertTree(TreeNode* root) {
if (!root) return NULL;
TreeNode *L = root->left, *R = root->right;
root->left = invertTree(R);
root->right = invertTree(L);
return root;
}
/* queue */
TreeNode* invertTree(TreeNode* root) {
if(!root) return NULL;
queue<TreeNode *> q;
q.push(root);
q.push(NULL);
while (!q.empty())
{
TreeNode *pCurr = q.front();
q.pop();
if (pCurr)
{
TreeNode *pLeft = pCurr->left;
pCurr->left = pCurr->right;
pCurr->right = pLeft;
if (pCurr->left) q.push(pCurr->left);
if (pCurr->right) q.push(pCurr->right);
}
else
{
if (q.empty()) break;
q.push(NULL);
}
}
return root;
}