leetcode 101. 对称二叉树 Symmetric Tree(使用c++/java/python)

本文介绍了一种通过递归算法判断二叉树是否为镜像对称的方法。使用C++、Java和Python三种语言实现,核心是定义一个辅助函数检查两棵树是否互为镜像。执行效率高,C++版本仅需8ms。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode-cn.com/problems/symmetric-tree/

https://leetcode.com/problems/symmetric-tree/

递归。利用一个函数判断两颗树是否镜像对称,即需要满足:

  1. 两树根节点相同
  2. 树1的左子树与树2的右子树镜像
  3. 树1的右子树与树2的左子树镜像

执行用时: c++ 8ms; java 15ms; python 48ms

 

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 {
public:
    bool isSymmetric(TreeNode* root) {
        if (root==NULL)
            return true;
        else
            return ismirror(root->left, root->right);
    }
    bool ismirror(TreeNode* n1,TreeNode* n2)
    {
        if (n1==NULL && n2==NULL)
            return true;
        if (n1==NULL || n2==NULL)
            return false;
        return (n1->val==n2->val)&&(ismirror(n1->left,n2->right))&&(ismirror(n1->right,n2->left));
    }
};

 

java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root==null)
            return true;
        else
            return ismirror(root.left,root.right);
    }
    public boolean ismirror(TreeNode root1,TreeNode root2)
    {
        if(root1==null && root2==null)
            return true;
        if(root1==null || root2==null)
            return false;
        return root1.val==root2.val && ismirror(root1.left,root2.right) && ismirror(root1.right,root2.left);
    }
}

 

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):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        else:
            return self.ismirror(root.left,root.right)
        
    def ismirror(self,root1,root2):
        if root1 is None and root2 is None:
            return True
        if root1 is None or root2 is None:
            return False
        return root1.val==root2.val and self.ismirror(root1.left,root2.right) and self.ismirror(root1.right,root2.left)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值