给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其自底向上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
https://github.com/soulmachine/leetcode
class Solution {
public:
void trasverse(TreeNode *root,int level,vector<vector<int>> &result){ // &小心别丢了
if(!root) return;
if(level>result.size()) result.push_back(vector<int>());
result[level-1].push_back(root->val);
trasverse(root->left,level+1,result);
trasverse(root->right,level+1,result);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> result;
trasverse(root,1,result);
reverse(result.begin(),result.end()); //转一下就完事了
return result;
}
};
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> result;
if(!root) return result;
vector<int> level;
queue<TreeNode*> p,q;
p.push(root);
while(!p.empty()){
while(!p.empty()){
TreeNode *node=p.front();
p.pop();
level.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
result.push_back(level);
level.clear();
swap(p,q);
}
reverse(result.begin(),result.end());
return result;
}
};