-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathinvert-binary-tree.cc
More file actions
42 lines (40 loc) · 870 Bytes
/
invert-binary-tree.cc
File metadata and controls
42 lines (40 loc) · 870 Bytes
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
// Invert Binary Tree
// recursive
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root) {
swap(root->left, root->right);
invertTree(root->left);
invertTree(root->right);
}
return root;
}
};
// variant of Morris post-order traversal
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
TreeNode aux(0), *p = &aux;
aux.left = root;
while (p) {
TreeNode *q = p->left;
if (q) {
while (q->right && q->right != p) q = q->right;
if (q->right == p) {
for (TreeNode *r = p->left; ; r = r->left) {
swap(r->left, r->right);
if (r == q) break;
}
q->left = NULL;
} else {
q->right = p;
p = p->left;
continue;
}
}
p = p->right;
}
return aux.left;
}
};