Day 17 代码随想录


110. 平衡二叉树

平衡二叉树
在这里插入图片描述

class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        leftH=self.getDepth(root.left)
        right=self.getDepth(root.right)
        cha=abs(leftH-right)
        if cha<=1 and self.isBalanced(root.right) and self.isBalanced(root.left):
            return True
        else:
            return False
    def getDepth(self,node):
        if not node:
            return 0
        leftHeight=self.getDepth(node.left)
        rightHeight=self.getDepth(node.right)
        Depth=1+max(leftHeight,rightHeight)
        return Depth

 这题的思路就是判断根节点的左右字数是否平衡,就转化为根节点左右子树的高度差。但是需要注意也要判断是否每个子节点都有子节点。体现在代码上的就是,就是把子树看做根节点看是否有高度差。

self.isBalanced(root.right) and self.isBalanced(root.left)

257. 二叉树的所有路径

二叉树的所有路径
在这里插入图片描述
 这题很明显使用递归来写,
(1) 找出重复的子问题。

前序遍历的顺序是:根节点、左子树、右子树。

在本题同样也是这个顺序:将根节点加入路径,递归左子树,递归右子树。

对于左子树和右子树来说,也都是同样的操作

class Solution:

    def getPaths(self, root, path, res):
        if not root:
            return
        # 节点值加入当前路径
        path += str(root.val)# 字符串格式
        # 如果当前节点是叶子节点,将当前路径加入结果集
        if root.left == None and root.right == None:
            res.append(path)
        # 如果当前节点不是叶子节点,继续遍历左子树和右子树。
        else:
            path += '->'
            self.getPaths(root.left, path, res)
            self.getPaths(root.right, path, res)

    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        
        res = []
        path=''
        self.getPaths(root, path, res)

        return res

404. 左叶子之和

左叶子之和
在这里插入图片描述

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        res=[]
        self.findleft(root,res)
        return sum(res)
    def findleft(self,root,res):
        if not root:
            return
        if root.left and not root.left.left and not root.left.right:
            res.append(root.left.val)
        self.findleft(root.left,res)
        self.findleft(root.right,res)

 我使用了递归函数,res是每个递归调用共享的变量,不是每次都创建一次。可以参考视频:carl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值