forked from AlgoStudyGroup/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvert-Binary-Tree.scala
40 lines (36 loc) · 974 Bytes
/
Invert-Binary-Tree.scala
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
class Question01 {
class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
var value: Int = _value
var left: TreeNode = _left
var right: TreeNode = _right
}
//space complexity O(1)
object Solution {
def invertTree(root: TreeNode): TreeNode = {
def recursiveInvert(root: TreeNode): Unit = {
if (root != null) {
val tmp = root.left
root.left = root.right
root.right = tmp
recursiveInvert(root.left)
recursiveInvert(root.right)
}
}
recursiveInvert(root)
root
}
}
//space complexity 0(n)
object Solution2 {
def invertTree(root: TreeNode): TreeNode = recursiveInvert(root)
def recursiveInvert(root: TreeNode): TreeNode = {
if (root == null) null
else {
val tmp = root.left
root.left = recursiveInvert(root.right)
root.right = recursiveInvert(tmp)
root
}
}
}
}