-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsymmetricBT.java
More file actions
62 lines (61 loc) · 1.83 KB
/
symmetricBT.java
File metadata and controls
62 lines (61 loc) · 1.83 KB
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
public class Solution {
public boolean isSymmetric(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return true;
return s(root.left,root.right);
}
public boolean s(TreeNode p,TreeNode q) {
if(p==null) return q==null;
if(q==null) return false;
return p.val==q.val&&s(p.left,q.right)&&s(p.right,q.left);
}
}
public class Solution {
List<Integer> value;
public boolean isSymmetric(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return true;
value = new ArrayList<Integer>();
in(root);
return p(value);
}
public void inorder(TreeNode root) {
if(root==null) return;
inorder(root.left);
value.add(root.val);
inorder(root.right);
}
public boolean palindrome(List<Integer> value) {
if(value.size()<=1) return true;
return value.get(0)==value.get(value.size()-1) && palindrome(value.subList(1,value.size()-1));
}
public boolean p(List<Integer> value) {
int size = value.size();
while(size>1) {
if(value.get(0)!=value.get(size-1)) return false;
value = value.subList(1,size-1);
size = value.size();
}
return true;
}
Stack<TreeNode> s;
public void in(TreeNode root) {
s = new Stack<TreeNode>();
s.push(root);
TreeNode x=root.left;
while(x!=null||!s.isEmpty()) {
if(x!=null) {
// push the non-null x first
s.push(x);
x = x.left;
}
else {
x = s.pop();
value.add(x.val);
x = x.right;
}
}
}
}