Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 339d403

Browse files
committed
Create Lt101.java
1 parent 8270e9a commit 339d403

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎LeetCode/Blind75/Lt101.java‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package Blind75;
2+
3+
import java.util.Stack;
4+
5+
class TreeNode {
6+
int val;
7+
TreeNode left;
8+
TreeNode right;
9+
TreeNode() {}
10+
TreeNode(int val) { this.val = val; }
11+
TreeNode(int val, TreeNode left, TreeNode right) {
12+
this.val = val;
13+
this.left = left;
14+
this.right = right;
15+
}
16+
}
17+
public class Lt101 {
18+
public static void main(String[] args) {
19+
20+
}
21+
22+
//Recursive solution fastest
23+
public boolean isSymmetric(TreeNode root) {
24+
25+
if(root == null){ return false;}
26+
27+
return checkSymmetric(root.left, root.right);
28+
}
29+
30+
public boolean checkSymmetric(TreeNode leftParent, TreeNode rightParent){
31+
32+
if(leftParent == null && rightParent == null){return true;}
33+
if(leftParent == null || rightParent == null){return false;}
34+
if(leftParent.val != rightParent.val){return false;}
35+
36+
return checkSymmetric(leftParent.left, rightParent.right) && checkSymmetric(leftParent.right, rightParent.left);
37+
38+
}
39+
//Iterative solution slower than recursion and with stack help
40+
public boolean isSymmetric2(TreeNode root) {
41+
if (root == null) return true;
42+
Stack<TreeNode> stack = new Stack<>();
43+
stack.push(root.left);
44+
stack.push(root.right);
45+
while (!stack.empty()) {
46+
TreeNode n1 = stack.pop(), n2 = stack.pop();
47+
if (n1 == null && n2 == null) continue;
48+
if (n1 == null || n2 == null || n1.val != n2.val) return false;
49+
stack.push(n1.left);
50+
stack.push(n2.right);
51+
stack.push(n1.right);
52+
stack.push(n2.left);
53+
}
54+
return true;
55+
}
56+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /