LeetCode OJ 107. Binary Tree Level Order Traversal II

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 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<List<Integer>> levelOrderBottom(TreeNode root) {
12         List<List<Integer>> list = new LinkedList<List<Integer>>();
13         if(root == null) return list;
14         
15         Queue<TreeNode> queue1 = new LinkedList<TreeNode>();
16         Queue<TreeNode> queue2 = new LinkedList<TreeNode>();
17         
18         queue1.offer(root);
19         
20         while(queue1.size()>0){
21             List<Integer> childlist = new ArrayList<Integer>();
22             while(queue1.size()>0){
23                 TreeNode node = queue1.remove();
24                 childlist.add(node.val);
25                 if(node.left!=null) queue2.offer(node.left);
26                 if(node.right!=null) queue2.offer(node.right);
27             }
28             list.add(0, childlist);
29             Queue<TreeNode> temp = queue1;
30             queue1 = queue2;
31             queue2 = temp;
32         }
33         
34         return list;
35     }
36 }

 

posted @ 2016-05-04 19:24  Black_Knight  阅读(186)  评论(0编辑  收藏  举报