class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root or not root.left and not root.right:
return True
elif not root.left or not root.right:
return False
stack1, stack2 = [], []
stack1.append(root.left)
stack2.append(root.right)
while stack1 and stack2:
left = stack1.pop()
right = stack2.pop()
if left.left and not right.right: return False
if left.right and not right.left: return False
if left.val != right.val:
return False
if left.left:
stack1.append(left.left)
if right.right:
stack2.append(right.right)
if left.right:
stack1.append(left.right)
if right.left:
stack2.append(right.left)
if stack1 or stack2:
return False
return Trueclass Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return helper(root.left, root.right);
}
private boolean helper(TreeNode left, TreeNode right) {
if (left == null && right == null) return true;
else if (left == null || right == null) return false;
if (left.val != right.val) return false;
return helper(left.left, right.right) && helper(left.right, right.left);
}
}