Skip to content

Commit 9466a23

Browse files
committed
Add Invert Binary Tree
1 parent 024ec33 commit 9466a23

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import java.util.Stack
2+
import ds.TreeNode
3+
4+
/*
5+
Definition of TreeNode:
6+
7+
data class TreeNode(
8+
var value: Int,
9+
var left: TreeNode? = null,
10+
var right: TreeNode? = null
11+
)
12+
*/
13+
14+
fun invertBinaryTreeIterative(root: TreeNode?): TreeNode? {
15+
if (root == null) return null
16+
val stack = Stack<TreeNode>()
17+
stack.push(root)
18+
while (stack.isNotEmpty()) {
19+
val node = stack.pop()
20+
// Swap the left and right subtrees of the current node.
21+
val temp = node.left
22+
node.left = node.right
23+
node.right = temp
24+
// Push the left and right subtrees onto the stack.
25+
if (node.left != null) {
26+
stack.push(node.left)
27+
}
28+
if (node.right != null) {
29+
stack.push(node.right)
30+
}
31+
}
32+
return root
33+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import ds.TreeNode
2+
3+
/*
4+
Definition of TreeNode:
5+
6+
data class TreeNode(
7+
var value: Int,
8+
var left: TreeNode? = null,
9+
var right: TreeNode? = null
10+
)
11+
*/
12+
13+
fun invertBinaryTreeRecursive(root: TreeNode?): TreeNode? {
14+
// Base case: If the node is null, there's nothing to invert.
15+
if (root == null) {
16+
return null
17+
}
18+
// Swap the left and right subtrees of the current node.
19+
val temp = root.left
20+
root.left = root.right
21+
root.right = temp
22+
// Recursively invert the left and right subtrees.
23+
invertBinaryTreeRecursive(root.left)
24+
invertBinaryTreeRecursive(root.right)
25+
return root
26+
}

0 commit comments

Comments
 (0)