LeetCode - 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]
]

Solution:

 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         // Start typing your Java solution below
13         // DO NOT write main() function
14         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
15         List<TreeNode> currLevel = new LinkedList<TreeNode>();
16         if(root != null) currLevel.add(root);
17         while(!currLevel.isEmpty()){
18             List<TreeNode> nextLevel = new LinkedList<TreeNode>();
19             ArrayList<Integer> list = new ArrayList<Integer>();
20             for(TreeNode n : currLevel){
21                 list.add(n.val);
22                 if(n.left != null) nextLevel.add(n.left);
23                 if(n.right != null) nextLevel.add(n.right);
24             }
25             currLevel = nextLevel;
26             result.add(list);
27         }
28         return result;
29     }
30 }

 

posted @ 2013-01-29 09:19  cradle  阅读(226)  评论(0编辑  收藏  举报