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,null,null,15,7],

3
/ \
9 20
/ \
15 7

return its level order traversal as:

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

分析:

使用队列。每出来一个将它的左右子节点依次加入。

代码:

public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) return result;
Queue<TreeNode> q = new LinkedList<TreeNode>();
TreeNode n = root;
q.offer(n);
while(!q.isEmpty()) {
List<Integer> levelList = new ArrayList<Integer>();
int num = q.size();
for (int i = 0; i < num; i++) {
TreeNode temp = q.poll();
levelList.add(temp.val);
if (temp.left != null) q.offer(temp.left);
if (temp.right != null) q.offer(temp.right);
}
result.add(levelList);
}
return result;
}
}

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD All Rights Reserved.

访客数 : | 访问量 :