Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / 2 2 / / 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / 2 2 3 3 Note: Bonus points if you could solve it both recursively and iteratively.
L: mirror tree:
Node mirror(Node node)
{
if (node == null)
return node;
/* do the subtrees */
Node left = mirror(node.left);
Node right = mirror(node.right);
/* swap the left and right pointers */
node.left = right;
node.right = left;
return node;
}
Traverse both left and right branches of the root symmetricaly and check if the values are equal.
想testcase, 如何遍历, 与谁比较, 是否为空,
就是判断值和关系是否相等
先序遍历
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> left = new Stack<>();
Stack<TreeNode> right = new Stack<>();
if (root.left != null && root.right == null || root.right != null && root.left == null) {
return false;
}
if (root.left == null && root.right == null) {
return true;
}
left.push(root.left);
right.push(root.right);
while (!left.isEmpty() && !right.isEmpty()) {
TreeNode cur1 = left.pop();
TreeNode cur2 = right.pop();
if (cur1.val != cur2.val) {
return false;
}
if (cur1.left != null) {
left.push(cur1.left);
}
if (cur2.right != null) {
right.push(cur2.right);
}
if (left.size() != right.size()) return false;
if (cur2.left != null) {
left.push(cur2.left);
}
if (cur1.right != null) {
right.push(cur1.right);
}
if (left.size() != right.size()) return false;
}
return left.size() == right.size();
}
递归
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
return helper(root.left, root.right);
}
public boolean helper(TreeNode p, TreeNode q){
if(p == null && q == null) {
return true;
}
if(p == null || q == null) {
return false;
}
return (
p.val == q.val && helper(p.left, q.right) && helper(p.right, q.left)
);
}