• [Leetcode]@python 101. Symmetric Tree


    题目链接

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

    题目原文

    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree is symmetric:

    But the following is not:

    题目大意

    给定一棵二叉树,判断这课二叉树是否对称

    解题思路

    从根节点出发,当存在左右子树的时候,判断左右子树的根节点的值是否相等,如果相等则递归判断左子树的左子树根节点与右子树的右子树根节点以及左子树的右子树根节点与右子树的左子树根节点是否相等。

    代码

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def symmetric(self, l, r):
            if l == None and r == None:
                return True
            if l and r and l.val == r.val:
                return self.symmetric(l.left, r.right) and self.symmetric(l.right, r.left)
            return False
    
        def isSymmetric(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            if root == None:
                return True
            else:
                return self.symmetric(root.left, root.right)
    
  • 相关阅读:
    Java8新特性详解
    RedisTemplate详解
    RestTemplate详解
    windows中将多个文本文件合并为一个文件
    commons-lang 介绍
    commons-cli介绍
    commons-collections介绍
    commons-codec介绍
    commons-beanutils介绍
    commons-io介绍
  • 原文地址:https://www.cnblogs.com/slurm/p/5239983.html
Copyright © 2020-2023  润新知