代码随想录算法训练营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
相关推荐
carpell4 分钟前
【深度学习基础】:VGG实战篇(图像风格迁移)
人工智能·python·深度学习·计算机视觉
一只帆記1 小时前
M1 Mac pip3 install错误记录
python·macos·pip
大魔王(已黑化)1 小时前
LeetCode —— 94. 二叉树的中序遍历
数据结构·c++·算法·leetcode·职场和发展
dudly1 小时前
Python全流程开发实战:基于IMAP协议安全下载个人Gmail邮箱内所有PDF附件
python·安全·小程序·pdf·个人开发
丰锋ff2 小时前
数据结构学习笔记
数据结构·笔记·学习
六点半8882 小时前
【蓝桥杯】第十六届蓝桥杯C/C++大学B组个人反思总结
c语言·c++·算法·蓝桥杯
✿ ༺ ོIT技术༻2 小时前
笔试强训:Day3
c++·笔记·算法
n33(NK)3 小时前
【算法基础】冒泡排序算法 - JAVA
java·算法·排序算法
niuge No.14 小时前
mindyolo填坑
python
帮帮志4 小时前
Python-pandas-操作Excel文件(读取数据/写入数据)及Excel表格列名操作详细分享
python·excel·pandas