题目来源:https://leetcode.com/problems/binary-tree-level-order-traversal/
问题描述
102. Binary Tree Level Order Traversal
Medium
Given a binary tree, return the level ordertraversal 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]
]
------------------------------------------------------------
题意
二叉树宽度优先遍历
------------------------------------------------------------
思路
队列。
由于不同深度的值要在不同的数组中输出,所以用了队列中用的元素用了level来维护节点的深度。
------------------------------------------------------------
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
class ListNode {
int val, level;
TreeNode left, right;
public ListNode (int val, int level, TreeNode left, TreeNode right) {
this.val = val;
this.level = level;
this.left = left;
this.right = right;
}
}
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return Collections.emptyList();
}
LinkedList<ListNode> queue = new LinkedList<ListNode>();
queue.add(new ListNode(root.val, 0, root.left, root.right));
int curLevel = 0;
List<List<Integer>> ret = new LinkedList<>();
List<Integer> levelList = new LinkedList<Integer>();
while (!queue.isEmpty()) {
ListNode head = queue.pollFirst();
if (head.left != null) {
queue.add(new ListNode(head.left.val, head.level+1, head.left.left, head.left.right));
}
if (head.right != null) {
queue.add(new ListNode(head.right.val, head.level+1, head.right.left, head.right.right));
}
if (head.level > curLevel) {
ret.add(levelList);
levelList = new LinkedList<Integer>();
curLevel = head.level;
}
levelList.add(head.val);
}
ret.add(levelList);
return ret;
}
}