-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvert_binary_tree.cpp
More file actions
116 lines (102 loc) · 2.44 KB
/
Copy pathinvert_binary_tree.cpp
File metadata and controls
116 lines (102 loc) · 2.44 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
////////////////////////////////////////////////////////////////////////////////
//
// Invert binary tree
// from https://leetcode.com/problems/invert-binary-tree/description/
//
// Description
// 4
// / \
// 2 7
// / \ / \
// 1 3 6 9
//
// to
// 4
// / \
// 7 2
// / \ / \
// 9 6 3 1
//
////////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <queue>
#include <stack>
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
////////////////////////////////////////////////////////////////////////////////
// recursive solution
TreeNode *invert_tree(TreeNode *root) {
if (root) {
invert_tree(root->left);
invert_tree(root->right);
std::swap(root->left, root->right);
}
return root;
}
////////////////////////////////////////////////////////////////////////////////
// non-recursive solution
TreeNode *invert_tree_1(TreeNode *root) {
std::stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()) {
TreeNode *p = stk.top();
stk.pop();
if (p) {
stk.push(p->left);
stk.push(p->right);
std::swap(p->left, p->right);
}
}
return root;
}
////////////////////////////////////////////////////////////////////////////////
// level traverse
std::vector<std::vector<int>> ret;
void build_vector(TreeNode *root, int depth) {
if (!root) return;
if (ret.size() == depth)
ret.push_back(std::vector<int>());
ret[depth].push_back(root->val);
build_vector(root->left, depth + 1);
build_vector(root->right, depth + 1);
}
void level_traverse(TreeNode *root) {
build_vector(root, 0);
for (int i = 0; i < ret.size(); ++i)
{
for (int j = 0; j < ret[i].size(); ++j)
std::cout << ret[i][j] << ' ';
std::cout << std::endl;
}
ret.clear();
}
int main(int argc, char** argv)
{
{
// root
// / \
// n1 n2
// / \ / \
// n3 n4 n5 n6
TreeNode *root = new TreeNode(4);
TreeNode *n1 = new TreeNode(2);
TreeNode *n2 = new TreeNode(7);
TreeNode *n3 = new TreeNode(1);
TreeNode *n4 = new TreeNode(3);
TreeNode *n5 = new TreeNode(6);
TreeNode *n6 = new TreeNode(9);
root->left = n1;
root->right = n2;
n1->left = n3;
n1->right = n4;
n2->left = n5;
n2->right = n6;
level_traverse(root);
invert_tree(root);
level_traverse(root);
}
return 0;
}