/**
* 101. Symmetric Tree
* 1. Time:O(n) Space:O(n)
* 2. Time:O(n) Space:O(n)
*/
// 1. Time:O(n) Space:O(n)
class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root,root);
}
private boolean isMirror(TreeNode p, TreeNode q){
if(p==null && q==null) return true;
if(p==null || q==null) return false;
return p.val==q.val && isMirror(p.left,q.right) && isMirror(p.right,q.left);
}
}
// 2. Time:O(n) Space:O(n)
class Solution {
public boolean isSymmetric(TreeNode root) {
Stack<TreeNode> s = new Stack<>();
s.push(root);
s.push(root);
while(!s.isEmpty()){
TreeNode p = s.pop();
TreeNode q = s.pop();
if(p==null && q==null) continue;
if(p==null || q==null) return false;
if(p.val!=q.val) return false;
s.push(p.left);
s.push(q.right);
s.push(p.right);
s.push(q.left);
}
return true;
}
}