-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0226_invert_binary_tree.kt
More file actions
50 lines (41 loc) · 1.27 KB
/
0226_invert_binary_tree.kt
File metadata and controls
50 lines (41 loc) · 1.27 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
// https://leetcode.com/problems/invert-binary-tree/description/
// O(n) space and time complexity using a DFS search and recursion.
/**
* 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 invertTree(root: TreeNode?): TreeNode? {
if (root == null) return null
var tempNode = root.left
root.left = root.right
root.right = tempNode
invertTree(root.left)
invertTree(root.right)
return root
}
}
// iterative BFS solution using a stack. Comes with an O(n) space and time complexity.
class Solution {
fun invertTree(root: TreeNode?): TreeNode? {
if (root == null) return null
val stack = ArrayDeque<TreeNode>()
stack.addFirst(root)
while (stack.isNotEmpty()) {
val element: TreeNode = stack.first();
stack.removeFirst();
val temp = element.left
element.left = element.right
element.right = temp
if (element.left != null) stack.add(element.left)
if (element.right != null) stack.add(element.right)
}
return root
}
}