【代码随想录算法训练营】第17天 | 第六章 二叉树(四)

主要内容

二叉树递归

题目

110. 平衡二叉树

题目描述

链接

思路分析

后序遍历的递归,从底向上
getDepthV2 相比 getDepth 进行了一点剪枝

代码

# 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 isBalanced(self, root: Optional[TreeNode]) -> bool:
        depth, rootis = self.getDepth(root)
        # rootis = self.getDepthV2(root) != -1
        return rootis
        
    def getDepth(self, node):
        if not node:
            return 0, True
        leftdepth, leftis = self.getDepth(node.left)
        rightdepth, rightis = self.getDepth(node.right)
        depth = 1 + max(leftdepth, rightdepth)
        depthis = abs(leftdepth - rightdepth) <= 1 and leftis and rightis
        return depth, depthis

    def getDepthV2(self, node):
        if not node:
            return 0

        leftdepth = self.getDepth(node.left)
        rightdepth = self.getDepth(node.right)
        # 剪枝了不再计算非平衡数
        if leftdepth == -1 or rightdepth == -1 or abs(leftdepth - rightdepth) > 1:
            return -1
        depth = 1 + max(leftdepth, rightdepth)
        return depth

#257. 二叉树的所有路径

添加链接描述

题目描述

思路分析

代码

# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []
        path = []
        if not root:
            return res
        self.findpath(root, path, res)
        return res

    def findpath(self, node, path, res):
        
        path.append(node.val)
        
        # 叶子节点,终止条件
        if not node.left and not node.right:
            res.append("->".join([str(p) for p in path]))
            return

        if node.left:
            self.findpath(node.left, path, res)
            path.pop()

        if node.right:
            self.findpath(node.right, path, res)
            path.pop()

隐藏回溯

# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []
        if not root:
            return res
        path = [root.val]
        self.findpath(root, path, res)
        return res

    def findpath(self, node, path, res):
        
        # path.append(node.val)
                
        # 叶子节点,终止条件
        if not node.left and not node.right:
            res.append("->".join([str(p) for p in path]))
            return

        if node.left:
            self.findpath(node.left, path + [node.left.val], res)
            #path.pop()

        if node.right:
            self.findpath(node.right, path + [node.right.val], res)
            #path.pop()

404.左叶子之和

题目描述

添加链接描述

思路分析

代码

# 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:
        return self.sumleft(root)
        # return self.res
    
    def sumleft(self, node):
        res = 0
        if node.left and not node.left.left and not node.left.right:
            res = node.left.val    
        left_sum = self.sumleft(node.left) if node.left else 0
        right_sum = self.sumleft(node.right) if node.right else 0
        return res + left_sum + right_sum

    # def sumleft(self, node, is_left):
        # # 终止条件
        # if not node.left and not node.right:  # 叶子节点
        #     if is_left:  # 左节点
        #         self.res += node.val
        # if node.left:
        #     self.sumleft(node.left, True)
        # if node.right:
        #     self.sumleft(node.right, False)
        
    # def sumleft(self, node):
    #     if node.left and not node.left.left and not node.left.right:
    #         self.res += node.left.val

    #     if node.left:
    #         self.sumleft(node.left)

    #     if node.right:
    #         self.sumleft(node.right)    


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值