Skip to content

Commit 7a46a45

Browse files
committed
Modified 2 solutions in trees
1 parent a02d023 commit 7a46a45

File tree

2 files changed

+27
-38
lines changed

2 files changed

+27
-38
lines changed

Trees/Problems/Inorder Traversal.java

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,27 +12,22 @@
1212
* }
1313
*/
1414
public class Solution {
15-
public ArrayList<Integer> inorderTraversal(TreeNode A) {
16-
ArrayList<Integer> arr = new ArrayList<>();
17-
Stack<TreeNode> stack = new Stack<>();
18-
19-
if (A == null) return arr;
20-
21-
while (true) {
22-
if (A != null) {
23-
stack.push(A);
24-
A = A.left;
25-
}
26-
else {
27-
if (stack.isEmpty()) {
28-
break;
29-
}
30-
A = stack.pop();
31-
arr.add(A.val);
32-
A = A.right;
33-
}
34-
}
35-
36-
return arr;
15+
public ArrayList<Integer> inorderTraversal(TreeNode A) {
16+
ArrayList<Integer> list = new ArrayList<>();
17+
Stack<TreeNode> stack = new Stack<>();
18+
while (A != null) {
19+
stack.push(A);
20+
A = A.left;
3721
}
22+
while (!stack.isEmpty()) {
23+
TreeNode removed = stack.pop();
24+
list.add(removed.val);
25+
TreeNode right = removed.right;
26+
while (right != null) {
27+
stack.push(right);
28+
right = right.left;
29+
}
30+
}
31+
return list;
32+
}
3833
}

Trees/Problems/Invert The Binary Tree.java

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,15 @@
1212
* }
1313
*/
1414
public class Solution {
15-
public TreeNode invertTree(TreeNode A) {
16-
if (A == null) return A;
17-
swap(A);
18-
return A;
19-
}
20-
21-
public void swap(TreeNode root) {
22-
if (root.left == null && root.right == null) {
23-
return;
24-
}
25-
TreeNode n1 = root.left;
26-
root.left = root.right;
27-
root.right = n1;
28-
29-
if (root.left != null) swap(root.left);
30-
if (root.right != null) swap(root.right);
15+
public TreeNode invertTree(TreeNode A) {
16+
if (A == null) {
17+
return null;
3118
}
19+
TreeNode left = A.left;
20+
A.left = A.right;
21+
A.right = left;
22+
invertTree(A.left);
23+
invertTree(A.right);
24+
return A;
25+
}
3226
}

0 commit comments

Comments
 (0)