给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)
/**
* 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: A tree
* @return: buttom-up level order a list of lists of integer
*/
public List<List<Integer>> levelOrderBottom(TreeNode root) {
// write your code here
LinkedList<List<Integer>> re = new LinkedList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
if (root == null)
return re;
stack.add(root);
while (!stack.isEmpty()) {
int n = stack.size();
List<Integer> temp = new ArrayList<>();
while (n-- > 0) {
TreeNode cur = stack.poll();
temp.add(cur.val);
if (cur.left != null)
stack.add(cur.left);
if (cur.right != null)
stack.add(cur.right);
}
re.addFirst(temp);
}
return re;
}
}