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

Appearance settings

Latest commit

 

History

History
History
67 lines (60 loc) · 1.98 KB

File metadata and controls

67 lines (60 loc) · 1.98 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class RecursiveSolution {
public boolean isSymmetricRecursive(TreeNode root) {
if (root == null) {
return true;
}
return this.check(root.left, root.right);
}
public boolean check(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if ((left == null && right != null) || (left != null && right == null) || (left.val != right.val)) {
return false;
}
return this.check(left.left, right.right) && this.check(left.right, right.left);
}
}
public class IterativeSolution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> left = new Stack<TreeNode>();
Stack<TreeNode> right = new Stack<TreeNode>();
TreeNode leftRoot = root.left;
TreeNode rightRoot = root.right;
while (left.isEmpty() == false || leftRoot != null) {
if (leftRoot != null) {
if (rightRoot == null) {
return false;
}
left.push(leftRoot);
right.push(rightRoot);
leftRoot = leftRoot.left;
rightRoot = rightRoot.right;
} else {
if (right.isEmpty() || rightRoot != null) {
return false;
}
TreeNode currLeft = left.pop();
TreeNode currRight = right.pop();
if (currLeft.val != currRight.val) {
return false;
}
leftRoot = currLeft.right;
rightRoot = currRight.left;
}
}
return right.isEmpty() && rightRoot == null;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.