forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree-level-order-traversal-ii(AC).cpp
54 lines (52 loc) · 1.28 KB
/
binary-tree-level-order-traversal-ii(AC).cpp
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
#include <algorithm>
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root : The root of binary tree.
* @return : buttom-up level order a list of lists of integer
*/
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
if (root == NULL) {
return ans;
}
maxDepth = 0;
calcDepth(root, 1);
ans.resize(maxDepth);
preorder(root, 0);
return ans;
}
private:
vector<vector<int> > ans;
int maxDepth;
void calcDepth(TreeNode *root, int depth) {
maxDepth = max(maxDepth, depth);
if (root->left != NULL) {
calcDepth(root->left, depth + 1);
}
if (root->right != NULL) {
calcDepth(root->right, depth + 1);
}
}
void preorder(TreeNode *root, int depth) {
ans[maxDepth - 1 - depth].push_back(root->val);
if (root->left != NULL) {
preorder(root->left, depth + 1);
}
if (root->right != NULL) {
preorder(root->right, depth + 1);
}
}
};