二叉树的层次遍历 II
题目
给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
样例
给出一棵二叉树 {3,9,20,#,#,15,7},
按照从下往上的层次遍历为:
题解
在上一题的基础上把每一层的节点列表先入栈,最后再转入列表,或者直接将结果反转。
/**
* 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>> list = new ArrayList<ArrayList<Integer>>();
if (root == null)
{
return list;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
Stack<ArrayList<Integer>> stack = new Stack<ArrayList<Integer>>();
q.add(root);
while (!q.isEmpty())
{
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = q.size();
for (int i=0;i<n;i++)
{
TreeNode t = q.poll();
arr.add(t.val);
if (t.left != null)
{
q.add(t.left);
}
if (t.right != null)
{
q.add(t.right);
}
}
stack.push(arr);
}
while (!stack.isEmpty())
{
list.add(stack.pop());
}
return list;
}
}
Last Update 2016.9.22