Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

101. Symmetric Tree

Posted on 2020-09-11 | Edited on 2021-01-22

LeetCode

Rrecursion

1
2
3
4
5
6
7
8
9
10
class Solution {
private boolean isMirror(TreeNode t1,TreeNode t2){
if(t1==null && t2==null) return true;
if(t1==null || t2==null) return false;
return t1.val==t2.val&&isMirror(t1.left,t2.right)&&isMirror(t1.right,t2.left);
}
public boolean isSymmetric(TreeNode root) {
return isMirror(root,root);
}
}

Iteration: BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean isSymmetric(TreeNode root) {
LinkedList<TreeNode> queue=new LinkedList<>();
queue.push(root);
queue.push(root);
while(!queue.isEmpty()){
TreeNode t1=queue.poll();
TreeNode t2=queue.poll();
if(t1==null && t2==null) continue;
if(t1==null || t2==null) return false;
if(t1.val!=t2.val) return false;
queue.push(t1.left);
queue.push(t2.right);
queue.push(t1.right);
queue.push(t2.left);
}
return true;
}
}

<1…161718…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%