【Symmetric Tree】

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;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值