102. Binary Tree Level Order Traversal

39次阅读

共计 1210 个字符,预计需要花费 4 分钟才能阅读完成。

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

难度:medium
题目:给定二叉树,返回其层次遍历结点值。
思路:队列 (FIFO)
Runtime: 1 ms, faster than 86.63% of Java online submissions for Binary Tree Level Order Traversal.Memory Usage: 37.5 MB, less than 100.00% of Java online submissions for Binary Tree Level Order Traversal.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) {val = x;}
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (null == root) {
return result;
}

Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int currentLevelCount = 1, nextLevelCount = 0;
List<Integer> currentLevelElements = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
currentLevelElements.add(node.val);
if (node.left != null) {
queue.add(node.left);
nextLevelCount++;
}
if (node.right != null) {
queue.add(node.right);
nextLevelCount++;
}
currentLevelCount–;
if (0 == currentLevelCount) {
result.add(currentLevelElements);
currentLevelElements = new ArrayList<>();
currentLevelCount = nextLevelCount;
nextLevelCount = 0;
}
}

return result;
}
}

正文完
 0