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

SOLUTION 1:

使用队列来解决,很直观。注意在每次换层的时候,新建一个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     public List<List<Integer>> levelOrder(TreeNode root) {
12         List<List<Integer>> ret = new ArrayList<List<Integer>>();
13         if (root == null) {
14             return ret;
15         }
16         
17         Queue<TreeNode> q = new LinkedList<TreeNode>();
18         q.offer(root);
19         
20         while (!q.isEmpty()) {
21             int size = q.size();
22             List<Integer> list = new ArrayList<Integer>();
23             for (int i = 0; i < size; i++) {
24                 TreeNode cur = q.poll();
25                 list.add(cur.val);
26                 
27                 if (cur.left != null) {
28                     q.offer(cur.left);
29                 }
30                 
31                 if (cur.right != null) {
32                     q.offer(cur.right);
33                 }
34             }
35             
36             ret.add(list);
37         }
38         
39         return ret;
40     }
41 }

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/LevelOrder.java

posted on 2014-12-22 20:24  Yu's Garden  阅读(531)  评论(0编辑  收藏  举报

导航