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