[leetcode]Binary Tree Level Order Traversal

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

算法思路:

最最基本的BFS,不做解释。

代码如下:

 1 public class Solution {
 2     public List<List<Integer>> levelOrder(TreeNode root) {
 3         List<List<Integer>> res = new ArrayList<List<Integer>>();
 4         if(root == null) return res;
 5         Queue<TreeNode> q = new LinkedList<TreeNode>();
 6         Queue<TreeNode> copy = new LinkedList<TreeNode>();
 7         q.offer(root);
 8         res.add(new ArrayList<Integer>(Arrays.asList(root.val)));
 9         while(!q.isEmpty()){
10             TreeNode node = q.poll();
11             if(node.left != null) copy.offer(node.left);
12             if(node.right != null) copy.offer(node.right);
13             if(q.isEmpty() && !copy.isEmpty()){
14                 List<Integer> list = new ArrayList<Integer>();
15                 while(!copy.isEmpty()){
16                     q.offer(copy.peek());
17                     list.add(copy.poll().val);
18                 }
19                 res.add(list);
20             }
21         }
22         return res;
23     }
24 }

 

posted on 2014-08-08 21:26  喵星人与汪星人  阅读(254)  评论(0编辑  收藏  举报