导航
导航
文章目录
  1. 题目
  2. 翻译
  3. 方法一
  4. 方法二

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

翻译

给出一颗二叉树,返回其层次遍历的节点值。(例如,从左到右,一层一层的)。
例如,给出一颗二叉树 {3,9,20,#,#,15,7},
   3
  / \
 9   20
    / \
   15  7
返回其层次遍历如下:
[
 [3],
 [9,20],
 [15,7]
]

方法一

利用两个队列,一个记录当前层,遍历当前层时,更新下一层节点。
每一层遍历结束之后,更新当前层为下一层,下一层为新队列,直到下一层没有节点为止:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
Queue<TreeNode> cur = new LinkedList<TreeNode>();
Queue<TreeNode> next = new LinkedList<TreeNode>();
cur.add(root);
while (!cur.isEmpty()) {
List<Integer> level = new ArrayList<Integer>();
while (!cur.isEmpty()) {
TreeNode node = cur.poll();
level.add(node.val);
if (node.left != null) next.add(node.left);
if (node.right != null) next.add(node.right);
}
res.add(level);
cur = next;
next = new LinkedList<TreeNode>();
}
return res;
}
}

方法二

只用一个队列,按照层次入队。
每一层入队之后,利用一个int记录这一层的size,出栈size个元素,即为当前层的list:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> level = new ArrayList<Integer>();
int size = queue.size();
while (size-- > 0) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
res.add(level);
}
return res;
}
}

参考:
http://www.programcreek.com/2014/04/leetcode-binary-tree-level-order-traversal-java/
http://www.oschina.net/code/snippet_2399500_48960