5
5
//
6
6
// For example:
7
7
// Given binary tree {3,9,20,#,#,15,7},
8
- // 3
9
- // / \
10
- // 9 20
11
- // / \
12
- // 15 7
8
+ // " 3 "
9
+ // " / \ "
10
+ // " 9 20 "
11
+ // " / \ "
12
+ // " 15 7 "
13
13
// return its bottom-up level order traversal as:
14
14
// [
15
15
// [15,7]
20
20
21
21
#include < iostream>
22
22
#include < vector>
23
+ #include < stack>
24
+
23
25
using namespace std ;
24
26
25
27
/* *
@@ -34,34 +36,75 @@ struct TreeNode {
34
36
35
37
class Solution {
36
38
public:
37
- vector<vector<int > > levelOrderBottom (TreeNode *root) {
39
+ vector<vector<int > > levelOrderBottom (TreeNode *root)
40
+ {
41
+ // return levelOrderBottom1(root);
42
+ return levelOrderBottom2 (root);
43
+ }
44
+
45
+ vector<vector<int > > levelOrderBottom1 (TreeNode *root)
46
+ {
38
47
vector<vector<int > > res;
39
48
vector<int > row;
40
- for (int level = maxHeight (root); level >= 1 ; level--) {
49
+ for (int level = maxHeight (root); level >= 1 ; level--)
50
+ {
41
51
row.clear ();
42
52
levelOrderBottomHelper (root, level, row);
43
53
res.push_back (row);
44
54
}
45
55
return res;
46
-
47
56
}
48
57
49
- int maxHeight (TreeNode *node) {
58
+ int maxHeight (TreeNode *node)
59
+ {
50
60
if (NULL == node) return 0 ;
51
61
return 1 + max (maxHeight (node->left ), maxHeight (node->right ));
52
62
};
53
63
54
- void levelOrderBottomHelper (TreeNode *node, int level, vector<int > &row) {
64
+ void levelOrderBottomHelper (TreeNode *node, int level, vector<int > &row)
65
+ {
55
66
if (level == 0 || node == NULL ) return ;
56
- if (level == 1 ) {
67
+ if (level == 1 )
68
+ {
57
69
row.push_back (node->val );
58
70
return ;
59
71
}
60
72
levelOrderBottomHelper (node->left , level-1 , row);
61
73
levelOrderBottomHelper (node->right , level-1 , row);
62
74
}
75
+
76
+ vector<vector<int > > levelOrderBottom2 (TreeNode *root)
77
+ {
78
+ vector<vector<int > > res;
79
+ if (!root) return res;
80
+
81
+ stack<vector<TreeNode*> > stk;
82
+ stk.push (vector<TreeNode*>(1 , root));
83
+ while (true )
84
+ {
85
+ vector<TreeNode*> row;
86
+ for (vector<TreeNode*>::iterator it = stk.top ().begin (); it != stk.top ().end (); ++it)
87
+ {
88
+ if ((*it)->left ) row.push_back ((*it)->left );
89
+ if ((*it)->right ) row.push_back ((*it)->right );
90
+ }
91
+ if (row.empty ()) break ;
92
+ stk.push (row);
93
+ }
94
+
95
+ while (!stk.empty ())
96
+ {
97
+ vector<int > row;
98
+ for (vector<TreeNode*>::iterator it = stk.top ().begin (); it != stk.top ().end (); ++it)
99
+ row.push_back ((*it)->val );
100
+ res.push_back (row);
101
+ stk.pop ();
102
+ }
103
+ return res;
104
+ }
63
105
};
64
106
65
- int main () {
107
+ int main ()
108
+ {
66
109
return 0 ;
67
110
}
0 commit comments