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

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)

 

全部评论

相关推荐

06-12 17:46
门头沟学院 Java
运营你豪哥:来说重点: ​1.项目前置,时间倒序。​​ 2.​项目描述强化结果与量化效果(STAR原则里的R)。​​ ​3.个人技能精炼,明确掌握程度,突出核心。​​ ​4.增加强有力开头的个人总结部分。​​ 5.​优化教育背景(成绩排名)、合并奖项与活动。​​
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务