题目描述:
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7],
C++代码如下:
/**
* 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>>res;
if(root==NULL)
return res;
queue<TreeNode*>q;
q.push(root);
while(!q.empty())
{
vector<int>r;
int size=q.size();
for(int i=0;i<size;i++)
{
TreeNode* t=q.front();
r.push_back(t->val);
q.pop();
if(t->left!=NULL)
{
q.push(t->left);
}
if(t->right!=NULL)
{
q.push(t->right);
}
}
res.push_back(r);
}
reverse(res.begin(),res.end());
return res;
}
};
JAVA代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> list = new LinkedList();//List<List<Integer>>的声明方式
if(root==null){
return list;
}
Queue<TreeNode> queue = new LinkedList<>();//Queue声明方式
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> r=new ArrayList<>();
int size=queue.size();
for(int i=0;i<size;i++){
TreeNode t=queue.poll();
r.add(t.val);
if(t.left!=null){
queue.offer(t.left);
}
if(t.right!=null){
queue.offer(t.right);
}
}
list.addFirst(r);
}
return list;
}
}
执行结果: