Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
Constraints:
- The number of nodes in the tree is in the range [1, 1000].
- -100 <= Node.val <= 100
Follow up: Could you solve it both recursively and iteratively?
completion:
/**
* 迭代判断二叉树是否围绕根对称
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root.left == null && root.right == null) {
return true;
} else if (root.left == null || root.right == null) {
return false;
} else {
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
Boolean isSymm = true;
stack1.add(root.left);
stack2.add(root.right);
while (!stack1.isEmpty() || !stack2.isEmpty()) {
TreeNode pop1 = stack1.pop();
TreeNode pop2 = stack2.pop();
if (pop1.val != pop2.val) {
isSymm = false;
break;
} else {
if (pop1.left != null && pop2.right != null) {
stack1.add(pop1.left);
stack2.add(pop2.right);
} else if (pop1.left == null && pop2.right == null) {
} else {
isSymm = false;
break;
}
if (pop1.right != null && pop2.left != null) {
stack1.add(pop1.right);
stack2.add(pop2.left);
} else if (pop1.right == null && pop2.left == null) {
} else {
isSymm = false;
break;
}
}
}
return isSymm;
}
}
}
/**
* 递归判断二叉树是否围绕根对称
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left, root.right);
}
public boolean compare(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
} else if (p == null || q == null) {
return false;
} else {
if (p.val == q.val) {
return compare(p.left, q.right) && compare(p.right, q.left);
} else {
return false;
}
}
}
}