剑指 Offer 28. 对称的二叉树

46 篇文章 0 订阅
19 篇文章 0 订阅

原题

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

​ 1

/ \

2 2

/ \ / \

3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

​ 1

/ \

2 2

\ \

3 3

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

  1. 直接比较 root->leftroot->right
  2. 再递归解决 root->left 的左子树和 root->right 的右子树,root->left 的右子树和 root->right 的左子树即可

代码

  • C++代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    bool isSymmetric(TreeNode *&A, TreeNode *&B) {
        if (A == nullptr && B == nullptr) {
            return true;
        }
        if (A == nullptr) {
            return false;
        }
        if (B == nullptr) {
            return false;
        }
        if (A->val != B->val) {
            return false;
        }
        return isSymmetric(A->left, B->right) && isSymmetric(A->right, B->left);
    }
public:
    bool isSymmetric(TreeNode* root) {
        if (!root) {
            return true;
        }
        return isSymmetric(root->left, root->right);
    }
};
  • Python代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def dfs(A, B):
            # A,B同时遍历到最后,返回True
            if not A and not B:
                return True
            # 只有A遍历到最后,返回False
            if not A:
                return False
            # 只有B遍历到最后,返回False
            if not B:
                return False
            # A.val 和 B.val不相等,返回False
            if A.val != B.val:
                return False
            # 继续比较A.left, B.right和A.right, B.left
            return dfs(A.left, B.right) and dfs(A.right, B.left)
        
        if not root:
            return True
        # 判断root.left和root.right即可
        return dfs(root.left, root.right)

时间复杂度 O ( N ) O(N) O(N) N N N 为树节点数量,左子树和右子树是同时遍历的,即调用了 N 2 \frac{N}{2} 2N 次。

空间复杂度 O ( N ) O(N) O(N)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值