Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
Solution1:
class Solution {
public boolean isSymmetric(TreeNode root) {
return root == null || isSymmetricHelp(root.left, root.right);
}
public boolean isSymmetricHelp(TreeNode left, TreeNode right) {
if (left == null)
return right == null;
if (right == null)
return false;
if (left.val != right.val) { //left.val不一定有值,所以要避免空指针异常
return false;
}
return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left);
}
}
Solution2://使用栈存放TreeNode,
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
Stack<TreeNode> s = new Stack<>();
s.push(root.left);
s.push(root.right);
while (!s.empty()) {
TreeNode n1 = s.pop();
TreeNode n2 = s.pop();
if (n1 == null && n2 == null) continue;
if (n1 == null || n2 == null || n1.val != n2.val) {
return false; //上边的if已经考虑了n1和n2都是null了,所以如果上述if条件不满足且n1或n2又出现 null,那么肯定是一个null一个有数值,所以返回false
}
stack.push(n1.left);
stack.push(n2.right);
stack.push(n1.right);
stack.push(n2.left);
}
return true;
}
原文:https://www.cnblogs.com/MarkLeeBYR/p/10537303.html