forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjdalma.kt
More file actions
58 lines (45 loc) ยท 1.36 KB
/
jdalma.kt
File metadata and controls
58 lines (45 loc) ยท 1.36 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class `invert-binary-tree` {
fun invertTree(root: TreeNode?): TreeNode? {
if (root == null) return null
return usingStack(root)
}
/**
* TC: O(n), SC: O(n)
*/
private fun usingDFS(node: TreeNode?): TreeNode? {
if (node == null) return null
val (left, right) = node.left to node.right
node.left = usingDFS(right)
node.right = usingDFS(left)
return node
}
/**
* TC: O(n), SC: O(n)
*/
private fun usingStack(node: TreeNode): TreeNode {
val stack= ArrayDeque<TreeNode>().apply {
this.add(node)
}
while (stack.isNotEmpty()) {
val now = stack.removeLast()
val tmp = now.left
now.left = now.right
now.right = tmp
now.left?.let { stack.add(it) }
now.right?.let { stack.add(it) }
}
return node
}
@Test
fun `์ ๋ฌ๋ ๋
ธ๋์ ํ์ ๋
ธ๋๋ค์ ๋ฐ์ ๋ ๊ฐ์ ๋ฐํํ๋ค`() {
val actual = TreeNode.of(4,2,7,1,3,6,9)
val expect = TreeNode.of(4,7,2,9,6,3,1)
invertTree(actual) shouldBe expect
val actual1 = TreeNode.of(1,2)
val expect1 = TreeNode.of(1,null,2)
invertTree(actual1) shouldBe expect1
}
}