LeetCode 0101. Symmetric Tree

问题简析

判断一个二叉树是否对称。
初步思路:设计一个递归函数,里面有两个子递归过程:
1)遍历左子树的左和右子树的右,只要有一层出现不相等,就返回false;
2)遍历左子树的右和右子树的左,只要有一层出现不相等,就返回false。

注意事项

1)对应位置结点都等于nullptr也合法。
2)一开始,算法设计错误,针对上述两个子递归过程分别设计了两个递归函数。结果对情况1)的子树,就只搜索他的左子树左和右子树右,对情况2)的子树就只搜索他的左子树右和右子树左。因此,对于测试用例:
[9, 25, 25, NULL, 95, 95, NULL, -100, NULL, NULL, -15]
就会因为无法遍历到-100和-15这一对结点,而导致判断错误。

题解

class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (root == nullptr) {
            return true;
        }
        TreeNode* leftChildren = root->left;
        TreeNode* rightChildren = root->right;

        // 左右子树都存在
        if (leftChildren != nullptr && rightChildren != nullptr &&
            leftChildren->val == rightChildren->val) {
            if (compare(leftChildren->left, rightChildren->right) &&
                compare(leftChildren->right, rightChildren->left)) {
                return true;
            }
            else {
                return false;
            }
        }
        // 只有一个根节点
        else if(leftChildren == nullptr && rightChildren == nullptr) {
            return true;
        }
        // 只有左子树/只有右子树
        else {
            return false;
        }
    }

    bool compare(TreeNode* node1, TreeNode* node2) {
        // 两个结点都为空
        if (node1 == nullptr && node2 == nullptr) {
            return true;
        }
        // 两个结点都非空,比较val,相同则继续深入比较,不同则直接返回false
        else if (node1 != nullptr && node2 != nullptr) {
            if (node1->val == node2->val) {
                return compare(node1->left, node2->right) && compare(node1->right, node2->left);
            }
            else {
                return false;
            }
        }
        // 一个为空,一个非空
        else {
            return false;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值