给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
样例
给出一棵二叉树 {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
按照从下往上的层次遍历为:
[
[15,7],
[9,20],
[3]
]
解题思路:和之前的层次遍历思想一样,用一个队列来保存节点,不停的从队列中取一层处理,插入到列表头部,以满足倒序输出
一刷ac
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: buttom-up level order a list of lists of integer
*/
public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
ArrayList<ArrayList<Integer>> rst = new ArrayList<ArrayList<Integer>>();
if(root == null) return rst;
LinkedList<TreeNode> nodelist = new LinkedList<TreeNode>();
nodelist.offer(root);
while(!nodelist.isEmpty()){
int size = nodelist.size();
ArrayList<Integer> al = new ArrayList<Integer>();
for(int i = 0; i < size; i++){
TreeNode node = nodelist.poll();
al.add(node.val);
if(node.left != null) nodelist.offer(node.left);
if(node.right != null) nodelist.offer(node.right);
}
rst.add(0,al);
}
return rst;
}
}