-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal.cc
More file actions
84 lines (72 loc) · 2.6 KB
/
BinaryTreeLevelOrderTraversal.cc
File metadata and controls
84 lines (72 loc) · 2.6 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
// https://oj.leetcode.com/problems/binary-tree-level-order-traversal/
namespace BinaryTreeLevelOrderTraversal {
// BFS based solution. Space O(n), Time O(n)
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > res;
if (root == NULL) {
return res;
}
TreeNode dummyNode(-1); // mark the end of level
TreeNode * dummy = &dummyNode;
queue<TreeNode *> q;
q.push(root);
q.push(dummy);
vector<int> *v = new vector<int>();
while (!q.empty()) {
TreeNode * cur = q.front();
q.pop();
if (cur != dummy) {
v->push_back(cur->val);
if (cur->left) {
q.push(cur->left);
}
if (cur->right) {
q.push(cur->right);
}
} else {
res.push_back(*v);
if (!q.empty()) {
q.push(dummy);
v = new vector<int>();
} else {
break;
}
}
}
return res;
}
};
// recursion based solution. Space complexity O(1) (if stack is not count in), time complexity is O(n),
// or more clear 2^(h + 1) - 2 - h, where h is the height of the tree.
class Solution2 {
public:
void traverse(TreeNode * curNode, vector<int> &curLevel, int curHeight, int targetHeight) {
if (curNode == NULL) {
return;
}
if (curHeight == targetHeight) {
curLevel.push_back(curNode->val);
return;
}
traverse(curNode->left, curLevel, curHeight + 1, targetHeight);
traverse(curNode->right, curLevel, curHeight + 1, targetHeight);
}
vector<vector<int> > levelOrder(TreeNode *root) {
vector<vector<int> > res;
int targetHeight = 1;
while (true) {
vector<int> curLevel;
traverse(root, curLevel, 1, targetHeight);
if (curLevel.empty()) {
break;
} else {
res.push_back(curLevel);
}
targetHeight++;
}
return res;
}
};
}