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],
]
解题思路: 使用BFS遍历树,将每一层放入一个ArrayList中。当一层结束后,将这个ArrayList插到最终的List的头部。
 1 /**
 2  * Definition for binary tree
 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 
12     public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
13         // Start typing your Java solution below
14         // DO NOT write main() function
15         ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
16         ArrayList<ArrayList<Integer>> r = new ArrayList<ArrayList<Integer>>();
17         if(root == null) return r;
18         queue.add(root);
19         TreeNode nl = new TreeNode(999);//999 是一个singal,表示一层结束了。
20         queue.add(nl);
21         ArrayList<Integer> cur = new ArrayList<Integer>();
22         while(queue.size() != 1){
23             TreeNode rn = queue.remove(0);
24             if(rn.val == 999){
25                 queue.add(nl);
26                 r.add(0,cur);
27                 cur = new ArrayList<Integer>();
28             }
29             else{
30                 if(rn.left != null) queue.add(rn.left);
31                 if(rn.right != null) queue.add(rn.right);
32                 cur.add(rn.val);
33             }
34         }
35         r.add(0,cur);
36         return r;
37     }
38 }

 

posted on 2013-09-14 05:35  Step-BY-Step  阅读(158)  评论(0编辑  收藏  举报

导航