Skip to content

Commit 2b9d2af

Browse files
authored
Merge pull request akgmage#1792 from akgmage/dev
add issymmetric in java
2 parents c9f7c8f + 160f613 commit 2b9d2af

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Trees/Binary Trees/is_symmetric.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Write a function that takes in a Binary Tree and returns if that tree is symmetrical. A tree is symmetrical
3+
if the left and right subtrees are mirror images of each other.
4+
*/
5+
import java.util.Stack;
6+
7+
public class BinaryTree {
8+
// Assume that BinaryTree has properties: left, right, and value.
9+
10+
public boolean isSymmetricalTreeIterative(BinaryTree tree) {
11+
Stack<BinaryTree> stackLeft = new Stack<>();
12+
Stack<BinaryTree> stackRight = new Stack<>();
13+
14+
// Initialize stackLeft with the left child of the root node
15+
// Initialize stackRight with the right child of the root node
16+
stackLeft.push(tree.getLeft());
17+
stackRight.push(tree.getRight());
18+
19+
// Perform mirror traversal of the left and right subtrees
20+
while (!stackLeft.isEmpty()) {
21+
BinaryTree left = stackLeft.pop();
22+
BinaryTree right = stackRight.pop();
23+
24+
if (left == null && right == null) {
25+
continue; // Both left and right subtrees are symmetric, continue to the next iteration
26+
}
27+
28+
if (left == null || right == null || left.getValue() != right.getValue()) {
29+
return false; // Asymmetry detected, tree is not symmetric
30+
}
31+
32+
// Push the children of left and right onto the respective stacks in reverse order
33+
stackLeft.push(left.getLeft());
34+
stackLeft.push(left.getRight());
35+
36+
stackRight.push(right.getRight());
37+
stackRight.push(right.getLeft());
38+
}
39+
40+
return true; // Tree is symmetric
41+
}
42+
43+
// Other methods and properties for BinaryTree class
44+
}

0 commit comments

Comments
 (0)