- leetcode BFS+DFS
- Leetcode PHP题解--D125 107. Binary
- leetcode:107. Binary Tree Level
- 107. Binary Tree Level Order Tra
- Binary Tree Zigzag Level Order T
- Leetcode-103题:Binary Tree Zigzag
- [Leetcode] 88. Binary Tree Zigza
- [Leetcode] 73. Binary Tree Zigza
- 107. Binary Tree Level Order Tra
- Q107 Binary Tree Level Order Tra
Description
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
My Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution{
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
vector<int> temp;
queue<TreeNode*> qu;
TreeNode* p = root;
if (p){
qu.push(p);
qu.push(NULL);
}
while(!qu.empty()){
while(qu.front()){
p = qu.front();
if (p->left){
qu.push(p->left);
}
if (p->right){
qu.push(p->right);
}
temp.push_back(p->val);
qu.pop();
}
qu.pop();
if (!temp.empty()){
ans.push_back(temp);
}
temp.clear();
if (qu.empty()){
break;
}
qu.push(NULL);
}
vector<int> t;
for (int i = 0; i < ans.size()/2; i++){
t = ans[i];
ans[i] = ans[ans.size()-i-1];
ans[ans.size()-i-1] = t;
}
return ans;
}
}
网友评论