给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
法一:最垃圾的方法,用stack来存放结果,最后把stack中数组放入res中,记住:stack不允许遍历,也不提供iterator,只能用top()和pop()
/**
* 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) {
queue<TreeNode*> q;
stack<vector<int>> sta;
vector<vector<int>> res;
if(root == NULL) return res;
q.push(root);
while(q.size()>0){
int s = q.size();
vector<int> level;
while(s--){
TreeNode* cur = q.front();
q.pop();
if(cur == NULL) continue;
level.push_back(cur->val);
q.push(cur->left);
q.push(cur->right);
}
if(level.size() != 0) sta.push(level);
}
while(sta.size()>0){
res.push_back(sta.top());
sta.pop();
}
return res;
}
};
法二:用reverse来直接翻转数组,并且只要创建一个level数组即可,在放入res之后,将level.clear()即可,就不用每层循环都创建一个,虽省空间,但费时
/**
* 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) {
queue<TreeNode*> q;
vector<vector<int>> res;
if(root == NULL) return res;
vector<int> level;
q.push(root);
while(q.size()>0){
int s = q.size();
while(s--){
TreeNode* cur = q.front();
q.pop();
if(cur == NULL) continue;
level.push_back(cur->val);
q.push(cur->left);
q.push(cur->right);
}
if(level.size() != 0) res.push_back(level);
level.clear();
}
reverse(res.begin(),res.end());
return res;
}
};