-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-level-order-traversal(AC).cpp
More file actions
54 lines (49 loc) · 1.33 KB
/
Copy pathbinary-tree-level-order-traversal(AC).cpp
File metadata and controls
54 lines (49 loc) · 1.33 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
// 3CE, 1AC, you fool!!! The code must be bug-free, well.. at least it should compile and runnnnnnnnnnn!
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
// I could use pre-order traversal to do this.
// Level-order traversal makes sense too.
// 1CE here, declaration of int i is MISSSING
for(int i = 0; i < result.size(); ++i){
result[i].clear();
}
result.clear();
if(root == nullptr){
return result;
}
preOrder(root, 0);
return result;
}
private:
vector<vector<int>> result;
void preOrder(TreeNode *root, int height) {
if(root == nullptr){
return;
}
// 1CE here, ) MISSING!!!
while(result.size() <= height){
result.push_back(vector<int>());
}
result[height].push_back(root->val);
if(root->left != nullptr){
preOrder(root->left, height + 1);
}
if(root->right != nullptr){
// 1CE here, spelling error, pre-order preOrder
// Don't rely on auto-complete, you're spoiled!!!
preOrder(root->right, height + 1);
}
}
};