|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | + |
| 6 | +class `binary-tree-level-order-traversal` { |
| 7 | + |
| 8 | + fun levelOrder(root: TreeNode?): List<List<Int>> { |
| 9 | + return if (root == null) emptyList() |
| 10 | + else usingDFS(root) |
| 11 | + } |
| 12 | + |
| 13 | + /** |
| 14 | + * TC: O(n), SC: O(n) |
| 15 | + */ |
| 16 | + private fun usingBFS(root: TreeNode): List<List<Int>> { |
| 17 | + val queue = ArrayDeque<TreeNode>().apply { |
| 18 | + this.add(root) |
| 19 | + } |
| 20 | + |
| 21 | + val result = mutableListOf<List<Int>>() |
| 22 | + while (queue.isNotEmpty()) { |
| 23 | + val values = mutableListOf<Int>() |
| 24 | + repeat(queue.size) { |
| 25 | + val node = queue.removeFirst() |
| 26 | + values.add(node.`val`) |
| 27 | + node.left?.also { queue.add(it) } |
| 28 | + node.right?.also { queue.add(it) } |
| 29 | + } |
| 30 | + result.add(values) |
| 31 | + } |
| 32 | + |
| 33 | + return result |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * TC: O(n), SC: O(n) |
| 38 | + */ |
| 39 | + private fun usingDFS(root: TreeNode): List<List<Int>> { |
| 40 | + |
| 41 | + fun dfs(node: TreeNode, result: MutableList<MutableList<Int>>, depth: Int) { |
| 42 | + if (depth >= result.size) { |
| 43 | + result.add(mutableListOf()) |
| 44 | + } |
| 45 | + result[depth].add(node.`val`) |
| 46 | + node.left?.also { dfs(it, result, depth + 1) } |
| 47 | + node.right?.also { dfs(it, result, depth + 1) } |
| 48 | + } |
| 49 | + |
| 50 | + return mutableListOf<MutableList<Int>>().apply { |
| 51 | + dfs(root, this, 0) |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + fun `트리 노드를 깊이 별로 반환한다`() { |
| 57 | + levelOrder(TreeNode.of(3,9,20,null,null,15,7)) shouldBe listOf( |
| 58 | + listOf(3), |
| 59 | + listOf(9,20), |
| 60 | + listOf(15,7) |
| 61 | + ) |
| 62 | + } |
| 63 | +} |
0 commit comments