-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path101. Symmetric Tree
24 lines (20 loc) · 951 Bytes
/
101. Symmetric Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public boolean isSymmetric(TreeNode root) {
return isSameTree(root.left, root.right);
}
public boolean isSameTree(TreeNode p, TreeNode q){
if(p==null && q==null) return true;
else if((p!=null && q==null) || (p==null && q!=null)) return false;
return (p.val==q.val && isSameTree(p.left, q.right) && isSameTree(p.right, q.left));
}
}
/*
LOGIC---
Symmetric binary tree is checking like the two halves of trees are same or not.
So, we think of the two halves as two seperate trees divided in half.
If these two divided trees are same they are symmetric.
But just a small differnece, becuase we are checking for mirror => the nodes will be laterally inverted.
So, left will become right and right will become left.
Meaning, left subtree's right node should be same as right subtree's left node.
Recursive conditon will be - isSameTree(p.left, q.right) && isSameTree(p.right, q.left)
*/