首页 > 编程语言 >代码随性训练营第十七天(Python)| 110.平衡二叉树、257. 二叉树的所有路径、404.左叶子之和

代码随性训练营第十七天(Python)| 110.平衡二叉树、257. 二叉树的所有路径、404.左叶子之和

时间:2023-10-30 16:45:03浏览次数:30  
标签:right return 随性 res self Python 二叉树 root left

110.平衡二叉树
1、递归法

class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if self.get_height(root) != -1: # -1 代表高度差大于 1
            return True
        else:
            return False

    def get_height(self, root):
        if root is None:
            return 0

        # 左
        left_height = self.get_height(root.left)
        if left_height == -1:
            return -1
        # 右
        right_height = self.get_height(root.right)
        if right_height == -1:
            return -1

        # 中
        res = abs(left_height-right_height)

        if res > 1:   # 实际高度差大于 1 , 标记不是平衡二叉树了。
            return -1
        else:          # 平衡二叉树求实际高度
            return 1 + max(left_height, right_height)

2、迭代法

class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        st = []
        if root:
            st.append(root)
        height_map = {}
        while st:
            node = st.pop()
            if node:
                # 中
                st.append(node)
                st.append(None)
                if node.right:
                    st.append(node.right)
                if node.left:
                    st.append(node.left)
            else:
                node = st.pop()
                left, right = height_map.get(node.left, 0), height_map.get(node.right, 0)
                if abs(left-right) > 1:
                    return False
                height_map[node] = 1 + max(left, right)
        return True

257. 二叉树的所有路径
1、递归回溯法

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []
        if root is None:
            return res
        path = []
        self.dfs(root, path, res)
        return res

    def dfs(self, root, path, res):
        # 中
        path.append(str(root.val))
        if not root.left and not root.right:
            res.append("->".join(path))
            return
            
        # 左
        if root.left:
            self.dfs(root.left, path, res)
            path.pop()  # path 是公共的,需要回溯

        # 右
        if root.right:
            self.dfs(root.right, path, res)
            path.pop()

2、隐藏递归法

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []
        if root is None:
            return res
        path = ""   # 赋值路径
        self.dfs(root, path, res)
        return res

    def dfs(self, root, path, res):
        path += str(root.val)
        if not root.left and not root.right:
            res.append(path)
            return

        if root.left:
            self.dfs(root.left, path + "->", res)
        if root.right:
            self.dfs(root.right, path + "->", res)

404.左叶子之和
思路:什么是左叶子节点

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        if not root.left and not root.right:
            return 0
        left_val = self.sumOfLeftLeaves(root.left) # 左
        if root.left and not root.left.left and not root.left.right:
            left_val = root.left.val
        right_val = self.sumOfLeftLeaves(root.right) # 右
        sum_left = left_val + right_val # 中
        return sum_left

标签:right,return,随性,res,self,Python,二叉树,root,left
From: https://www.cnblogs.com/yixff/p/17793904.html

相关文章

  • Python Lambda 用法大全
    一、Lambda表达式基础Lambda的组成分为三部分lambdaarguments:expressionarguments为Lambda表达式的参数列表,多个参数使用逗号分隔;expression则是Lambda表达式的返回值表达式。Lambda表达式的基本用法:(lambdax,y:x+y)(1,2)#输出3(lambdax:x*x)(3)#输出9......
  • python 飞书 获取飞书租户访问令牌 自定义机器人 向webhook_url发送POST请求
    importjsonimportrequestswebhook_url=post_data=#见应用凭证#获取飞书租户访问令牌,用于调用飞书开放平台的其他API接口#url:飞书开放平台的获取租户访问令牌的API接口地址url=r"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"r=......
  • python爬虫知识体系80页md笔记,0基础到scrapy项目高手,第(2)篇:http协议复习精讲
    本文主要学习一下关于爬虫的相关前置知识和一些理论性的知识,通过本文我们能够知道什么是爬虫,都有那些分类,爬虫能干什么等,同时还会站在爬虫的角度复习一下http协议。完整体系笔记直接地址:请移步这里共8章,37子模块,总计5.6w+字今天这一篇主讲:爬虫基础本阶段本文主要学......
  • 查看python中import可以支持的格式引用
    importimportlib.machineryformat_list=importlib.machinery.all_suffixes()print(format_list)so是linux可以加载的文件,windows是pyc ......
  • python json5 转 json
    JSON5是JSON的超集,它的目标是使JSON更易于人类阅读和编写。JSON5引入了一些在ECMAScript5中的一些特性,如注释、尾逗号、单引号等¹。要将JSON5转换为JSON,你需要删除JSON5中的所有注释、尾逗号和单引号,并确保所有的键都被双引号包围。这可以通过编程实现,也可以使用在......
  • 二叉树概念和操作
    二叉树定义二叉树(BinaryTree)是n(n>=0)个结点所构成的集合,它或为空树(n=0);或为非空树,对于非空树$T$:有且仅有一个称之为根的结点除根节点以外的其余结点分为两个互不相交的子集$T_1$和$T_2$,分别称为$T$的左子树和右子树,且$T_1$和$T_2$本身又是二叉树二叉树性质及存储结构通过......
  • shell脚本里如何设置Python的环境变量
    在shell脚本中设置Python的环境变量可以通过以下几个步骤来完成。首先,需要确定Python的安装路径。可以通过以下命令来查找Python的安装路径:该命令会返回Python可执行文件的路径,例如:/usr/bin/python。whichpython接下来,将Python的安装路径添加到PATH环境变量中。PA......
  • 平衡二叉树AVL
    在计算机科学中,AVL树是最早被发明的自平衡二叉查找树。在AVL树中,任一节点对应的两棵子树的最大高度差为1,因此它也被称为高度平衡树。查找、插入和删除在平均和最坏情况下的时间复杂度都是$O(logn)$。所以我们可知,AVL树首先是二叉查找树(BST),不了解BST的同学可以了解一下,因为AVL树......
  • Python构造代理IP池提高访问量
    前言爬虫程序是批量获取互联网上的信息的重要工具,在访问目标网站时需要频繁发送请求,为了避免被目标网站封禁IP地址,我们需要使用代理IP来代替自己的IP地址进行访问。本文将介绍如何使用Python构建代理IP池,让爬虫程序更加稳定和高效地运行。一、代理IP是什么代理IP是指由第......
  • Python如何去掉字符串空格?
    在Python中,当我们使用Python处理字符串时,经常会遇到字符串中包含空格的情况,那么Python如何去掉字符串空格?有多种方法可以从Python字符串中删除空格,以下是详细内容介绍。1、使用strip()方法它是一个Python内置函数,可以用来去除字符串开头和结尾的空格。例如,以下代码将......