代码随想录算法训练营day12(二叉树)

华子目录

平衡二叉树

思路

  • 什么是平衡二叉树左子树的高度右子树的高度相差不超过1
  • isBalanced用来判断是否为平衡二叉树,如果当前树不是平衡二叉树,直接返回最终结果False。如果当前树为平衡二叉树,就再判断其左右子树左右子树也必须为平衡二叉树
  • cal_depth用来求一个子树的最大深度,这是之前讲过的内容(求最大深度、最小深度、节点个数,都是基础内容
python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def cal_depth(self,root):
        cur = root
        if not cur:
            return 0
        leftHeight = self.cal_depth(cur.left)
        rightHeight = self.cal_depth(cur.right)
        height = 1 + max(leftHeight, rightHeight)
        return height
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        left_depth = self.cal_depth(root.left)    # 求出左子树的深度
        right_depth = self.cal_depth(root.right)   # 求出右子树的深度
        if abs(left_depth - right_depth) > 1:    # 相差
            return False
        return self.isBalanced(root.left) and self.isBalanced(root.right)

二叉树的所有路径

思路

  • 这道题是使用回溯来求解,第一次接触回溯法,多看看视频来理解。

具体写法

  • 递归的写法里传入三个参数(1)当前处理的节点(2)当前的路径(3)总的结果集
  • 递归的终止条件:当节点叶子节点时,把当前路径加入结果集
  • 递归的单层处理当node有左节点时递归处理左节点处理结束后回溯当node有右节点时递归处理右节点处理结束后回溯
python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def travel(self, node, path, res):
        if not node.left and not node.right:   # node为叶子节点
            path = [str(x) for x in path]
            res.append('->'.join(path))   # 将某一条路径加入到总的结果集当中

        if node.left:  # 左有值
            path.append(node.left.val)
            self.travel(node.left, path, res)
            path.pop() # 某一条路线递归结束后,弹出
        if node.right:  # 右有值
            path.append(node.right.val)
            self.travel(node.right, path, res)
            path.pop()  # 某一条路径递归结束后,弹出

    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        cur = root
        if not cur:
            return []
        res = []   # 记录所有路径
        path = [cur.val]  # 记录当前路径
        self.travel(cur,path, res)
        return res

左叶子之和

思路

  • 使用后序遍历
python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        if not root:  # 终止条件,当前节点为空
            return 0
        if not root.left and not root.right:  # 终止条件,当前节点是叶子节点
            return 0
        left_num = self.sumOfLeftLeaves(root.left)
        right_num = self.sumOfLeftLeaves(root.right)

        cur_num = 0
        if root.left and not root.left.left and not root.left.right: # # root.left 是左叶子
            cur_num = root.left.val     # 记录左叶子的值

        return cur_num + left_num + right_num  # 三部分的汇总

完全二叉树的节点个数

思路

  • 完全二叉树当成二叉树去计算,使用后序遍历去计算
python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        cur = root
        if not cur:
            return 0
        left_num = self.countNodes(cur.left)
        right_num = self.countNodes(cur.right)
        result = left_num + right_num + 1   # 核心
        return result
相关推荐
拳里剑气16 分钟前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
颜酱25 分钟前
09 | 重构项目结构
人工智能·python·langchain
ysa0510301 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
shwill1231 小时前
PID 算法(三)--- 增量 PID ↔ 单神经元 PID 等价映射
linux·算法
Sisphusssss2 小时前
香橙派5plus GPIO
linux·python·ubuntu
wabs6662 小时前
关于图论【卡码网110.字符串迁移的思考】
数据结构·算法·图论
颜酱3 小时前
08 | 把维度值同步到 Elasticsearch(生成阶段)
人工智能·python·langchain
hanlin033 小时前
刷题笔记:力扣第242、349题(哈希表)
笔记·算法·leetcode
久久学姐3 小时前
基础转码学 AI:Java+Python 双语言入门,3 个月可落地实战项目
java·python·ai·转码·实战项目
ZHOU_WUYI3 小时前
4. light wam 模型loss计算过程
开发语言·人工智能·python