(LeetCode) 102. Binary Tree Level Order Traversal

102. Binary Tree Level Order Traversal

  • Explore : Interview > Top Interveiw Questions > Easy Collection
  • 분류 : Trees
  • 난이도 : Easy

Problem

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1

1
2
Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2

1
2
Input: root = [1,2,2,null,3,null,3]
Output: false

Constraints

  • The number of nodes in the tree is in the range [1, 1000].
  • -100 <= Node.val <= 100

Solution

Exapnder
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
32
33
34
35
36
37
/**
* 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
* }
*/
class Solution {
fun levelOrder(root: TreeNode?): List<List<Int>> {
var result: MutableList<List<Int>> = mutableListOf()
if (root == null) {
return result
}

var queue: Queue<TreeNode> = LinkedList()
queue.add(root)

while (queue.isNotEmpty()) {
var elementArray: MutableList<Int> = mutableListOf()
for (i in 0 until queue.size) {
var node: TreeNode = queue.poll()
elementArray.add(node.`val`)
node.left?.let {
queue.add(it)
}
node.right?.let {
queue.add(it)
}
}
result.add(elementArray)
}
return result
}
}

Point of Thinking

  • Level 하나당 queue에 모든 노드를 쌓은 뒤, 한 번 순회할때마다 리스트를 만들어서 반환한다.