[LeetCode] 102. Binary Tree Level Order Traversal(二叉树的中序遍历)
-
Difficulty: Medium
-
Related Topics: Tree, Breadth-first Search
-
Link: https://leetcode.com/problems/binary-tree-level-order-traversal/
Description
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]
]
Solution
/**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
import java.util.*
class Solution {
fun levelOrder(root: TreeNode?): List<List<Int>> {
if (root == null) {
return emptyList()
}
val queue: Queue<TreeNode> = ArrayDeque()
queue.offer(root)
val result = arrayListOf<List<Int>>()
while (queue.isNotEmpty()) {
val levelNodes = queue.size
val curList = arrayListOf<Int>()
for (i in 1..levelNodes) {
val node = queue.poll()
curList.add(node.`val`)
node.left?.let { queue.offer(it) }
node.right?.let { queue.offer(it) }
}
result.add(curList)
}
return result
}
}