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] ]
/**
* 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:
void check(TreeNode*a,vector<vector<int>>&ans,int dep){
if(a == NULL) return ;
if(ans.size() <= dep){
vector<int> ax;
ans.push_back(ax);
}
ans[dep].push_back(a->val);
check(a->left,ans,dep+1);
check(a->right,ans,dep+1);
}
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> ans;
check(root,ans,0);
for(int i = 0;i < ans.size() / 2; i++){
swap(ans[i],ans[ans.size()-1-i]);
}
return ans;
}
};
本文介绍了一种从叶节点到根节点的层次遍历二叉树的方法,并提供了一个具体的C++实现示例。该算法首先通过递归方式获取各层级的节点值,然后反转结果以实现从底部向顶部的层次遍历。
312

被折叠的 条评论
为什么被折叠?



