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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
题意:从下往上,将每一层从左往右存储
分类:二叉树
解法1:层次遍历,使用队列进行层次遍历,关键在于标记每一层结束的位置。使用了ceng来标记,每次low==ceng,说明该层遍历完毕,将ceng更新为当前high
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
if(root == null) return res;
List<Integer> t = new ArrayList<Integer>();
int low = 0;
int high = 0;
int ceng = 0;
stack.add(root);
t.add(root.val);
res.add(t);
t = new ArrayList<Integer>();;
while(low<=high){
TreeNode cur = stack.get(low);
if(cur.left!=null){
stack.add(cur.left);
t.add(cur.left.val);
high++;
}
if(cur.right!=null){
stack.add(cur.right);
t.add(cur.right.val);
high++;
}
if(low==ceng){
if(t.size()!=0) res.addFirst(t);;
t = new ArrayList<Integer>();
ceng = high;
}
low++;
}
return res;
}
}
解法2:层次遍历,而辨别层结束的方法是,在每层结尾,都添加一个标记元素,遍历时遇到标记元素,说明该层遍历结束
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
List<Integer> item = new ArrayList<Integer>();
if(root==null) return res;
queue.add(root);
TreeNode mark = new TreeNode(-1);//哨兵元素,用于标记某层的结束
queue.add(mark);
while(queue.size()>1){//因为有哨兵,所以至少是1,然而这样最后一层会没有被加入res
TreeNode cur = queue.poll();
if(cur!=mark){
item.add(cur.val);
if(cur.left!=null) queue.add(cur.left);
if(cur.right!=null) queue.add(cur.right);
}else{//当前为哨兵元素
res.addFirst(new ArrayList<Integer>(item));
item.clear();
queue.add(mark);
}
}
res.addFirst(item);//最后一层
return res;
}
}