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
-
-
-
-
-
-
-
-
-
- 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:层次遍历,而辨别层结束的方法是,在每层结尾,都添加一个标记元素,遍历时遇到标记元素,说明该层遍历结束
-
-
-
-
-
-
-
-
-
- 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){
- 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;
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46378669