题目:
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] ]思路:
这题不难,按层遍历一个queue就行,如果要反向输出,再用一个stack调整一下顺序就好了!
/**
* 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>> v_e;
if (root==NULL)
return v_e;
else{
TreeNode* t;
queue<TreeNode*> q;
q.push(root);
t = q.front();
stack<vector<int>> s;
while (!q.empty()){
int size = q.size();
vector<int> v;
for (int i = 0; i < size;i++){
t = q.front();
v.push_back(t->val);
q.pop();
if(t->left!=NULL)
q.push(t->left);
if(t->right!=NULL)
q.push(t->right);
}
s.push(v);
}
while(!s.empty()){
v_e.push_back(s.top());
s.pop();
}
return v_e;
}
}
};