Skip to content

Commit bc245dd

Browse files
committed
add: InvertBinaryTreeRecursive and InvertBinaryTreeIterative
1 parent 54ee678 commit bc245dd

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.util.Stack;
2+
3+
import DS.TreeNode;
4+
5+
/*
6+
// Definition of TreeNode:
7+
class TreeNode {
8+
public int val;
9+
public TreeNode left;
10+
public TreeNode right;
11+
public TreeNode(int val) {
12+
this.val = val;
13+
}
14+
}
15+
*/
16+
17+
public class InvertBinaryTreeIterative {
18+
public TreeNode invertBinaryTreeIterative(TreeNode root) {
19+
if (root == null) {
20+
return null;
21+
}
22+
Stack<TreeNode> stack = new Stack<>();
23+
stack.push(root);
24+
while (!stack.isEmpty()) {
25+
TreeNode node = stack.pop();
26+
// Swap the left and right subtrees of the current node.
27+
TreeNode tmp = node.left;
28+
node.left = node.right;
29+
node.right = tmp;
30+
// Push the left and right subtrees onto the stack.
31+
if (node.left != null) {
32+
stack.push(node.left);
33+
}
34+
if (node.right != null) {
35+
stack.push(node.right);
36+
}
37+
}
38+
return root;
39+
}
40+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import DS.TreeNode;
2+
3+
/*
4+
// Definition of TreeNode:
5+
class TreeNode {
6+
public int val;
7+
public TreeNode left;
8+
public TreeNode right;
9+
public TreeNode(int val) {
10+
this.val = val;
11+
}
12+
}
13+
*/
14+
15+
public class InvertBinaryTreeRecursive {
16+
public TreeNode invertBinaryTreeRecursive(TreeNode root) {
17+
// Base case: If the node is null, there's nothing to invert.
18+
if (root == null) {
19+
return root;
20+
}
21+
// Swap the left and right subtrees of the current node.
22+
TreeNode tmp = root.left;
23+
root.left = root.right;
24+
root.right = tmp;
25+
// Recursively invert the left and right subtrees.
26+
invertBinaryTreeRecursive(root.left);
27+
invertBinaryTreeRecursive(root.right);
28+
return root;
29+
}
30+
}

0 commit comments

Comments
 (0)