代码随想录算法训练营第十七天 | 110.平衡二叉树 257. 二叉树的所有路径 404.左叶子之和

110.平衡二叉树

题解:https://programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC

class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        return self.getDepth(root) != -1
    def getDepth(self, node):
        if not node:
            return 0
        left_depth = self.getDepth(node.left)
        right_depth = self.getDepth(node.right)
        if left_depth == -1 or right_depth == -1 or abs(left_depth - right_depth) > 1:
            return -1
        else:
            return max(left_depth,right_depth) + 1

257. 二叉树的所有路径

题解:https://programmercarl.com/0257.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%89%80%E6%9C%89%E8%B7%AF%E5%BE%84.html#%E6%80%9D%E8%B7%AF

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        result = []
        path = []
        if not root:
            return result
        else:
            self.getPath(root,path,result)
            return result
    def getPath(self,cur,path,result):
        path.append(str(cur.val))
        if not cur.left and not cur.right:
            result.append('->'.join(path))
            return
        if cur.left:
            self.getPath(cur.left, path, result)
            path.pop()
        if cur.right:
            self.getPath(cur.right,path, result)
            path.pop()

404.左叶子之和

题解:https://programmercarl.com/0404.%E5%B7%A6%E5%8F%B6%E5%AD%90%E4%B9%8B%E5%92%8C.html#%E6%80%9D%E8%B7%AF

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        if root.left is None and root.right is None:
            return 0
        leftValue = self.sumOfLeftLeaves(root.left)  # 左
        if root.left and not root.left.left and not root.left.right:  # 左子树是左叶子的情况
            leftValue = root.left.val
        rightValue = self.sumOfLeftLeaves(root.right)  # 右
        sum_val = leftValue + rightValue  # 中
        return sum_val
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值