Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
 
 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     public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
12         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         ArrayList<TreeNode> queue = new ArrayList<TreeNode>();
15         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
16         if(root == null) return result;
17         queue.add(root);
18         TreeNode nl = new TreeNode(Integer.MIN_VALUE);
19         queue.add(nl);
20         ArrayList<Integer> cur = new ArrayList<Integer>();
21         while(queue.size() != 1){
22             TreeNode rn = queue.remove(0);
23             if(rn.val == Integer.MIN_VALUE){
24                 queue.add(nl);
25                 result.add(cur);
26                 cur = new ArrayList<Integer>();
27             }
28             else{
29                 if(rn.left != null) queue.add(rn.left);
30                 if(rn.right != null) queue.add(rn.right);
31                 cur.add(rn.val);
32             }
33         }
34         result.add(cur);
35         return result;
36     }
37 }

 

posted on 2013-11-16 05:18  Step-BY-Step  阅读(193)  评论(0编辑  收藏  举报

导航