File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments