代码训练营 DAY 18 | 二叉树 part05

今日第一题:

513. Find Bottom Left Tree Value

用层序循环模板改改就行

# symmertic
from collections import deque

class Solution(object):
    def findBottomLeftValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        queue = collections.deque([root])
        
        result = 0
        
        while queue:
            for i in range(len(queue)):
                node = queue.popleft()
                if i == 0:
                    result = node.val
                
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        
        return result
        
        

今日第二题:

112. Path Sum

对比一下找所有路径、找到达数字的路径、到达数字的所有路径

# 二叉树的所有路径:
# Definition for a binary tree node.
class Solution:
    def traversal(self, cur, path, result):
        path.append(cur.val)  # 中
        
        if not cur.left and not cur.right:  # 到达叶子节点
            sPath = '->'.join(map(str, path))
            result.append(sPath)
            # 这里为什么return 空
# the reason for returning an empty list when the root is None is to handle the case where there is no tree 
# (empty tree) and to ensure that the function doesn't perform unnecessary work when there are no paths to find. 
# This is a common practice in coding to handle edge cases gracefully and avoid unnecessary computations.
            return
        
        if cur.left:  # 左
            self.traversal(cur.left, path, result)
            path.pop()  # 回溯
        
        if cur.right:  # 右
            self.traversal(cur.right, path, result)
            path.pop()  # 回溯

    def binaryTreePaths(self, root):
        result = []
        path = []
        if not root:
            return result
        self.traversal(root, path, result)
        return result
# traversal

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def hasPathSum(self, root, targetSum)->bool:
        # 为什么要加一个-〉bool
        # 是idea自己加的,在leetcode里要自己去掉
        return self.traversal(root, targetSum - root.val)
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: bool
        """
    
    def traversal(self, cur: TreeNode, count:int)->bool:
        # 达到叶子节点 and count 减去为0了 which means equal to targetSum
        if not cur.left and not cur.right and count == 0:
            return True
        
        # 达到叶子结点:返回
        if not cur.left and not cur.right:
            return False
        
        if cur.left:
            count -= cur.left.val
            if self.traversal(cur.left, count):# 递归,处理节点
                return True
            count += cur.left.val# 回溯,撤销处理结果
        
        if cur.right:
            count -= cur.right.val
            if self.traversal(cur.right, count):# 递归,处理节点
                return True
            count += cur.right.val# 回溯,撤销处理结果
        
        return False
    
        
        
        
# 113 path sum2
# 113路径之和2: 找到所有满足sum的所有子路径
# 113.路径总和ii要遍历整个树,找到所有路径,所以递归函数不要返回值!

class Solutioin:
    def __init__(self):
        self.result = []
        self.path = []
    
    def traversal(self,cur,count):
        if not cur.left and not cur.right and count == 0:
            self.result.append(self.path[:])
# This is a common way to capture a snapshot of the current path and store it in the result list.
#`self.path[:]` creates a shallow copy of the `self.path` list. This copy contains the same elements as `self.path`, but it's a separate list object.
            return 

        if not cur.left and not cur.right: # 遇到叶子节点而没有找到合适的边,直接返回
            return
        
        
        if cur.left:
            self.path.append(cur.left.val)
            count -= cur.left.val
            self.traversal(cur.left,count)
            count += cur.left.val
            self.path.pop()
        
        if cur.right:
            self.path.append(cur.right.val)
            count -= cur.right.val
            self.traversal(cur.right,count)
            count += cur.right.val
            self.path.pop()
            
        
    def pathSum(self,root,sum):
        self.result.clear()
        self.path.clear()
        
        if not root:
            return self.result
        self.path.append(root.val)
        self.traversal(root,sum-root.val)
        return self.result


今日第三题:【重点】

106. Construct Binary Tree from Inorder and Postorder Traversal

看懂了,手不会写,先记答案吧

class Solution:
    def buildTree(self,inorder):
        if not postoder:
            return None
        
        root_val = postorder[-1]
        root = TreeNode(root_val)
        
        separator_idx = inorder.index(root_val)
        
        inorder_left = inorder[ : separator_idx]
        inorder_right = inorder[separator_idx+1 : ]
        
        postorder_left = postorder[ : len(inorder_left)]
        postorder_right = potorder[len(inorder_left): len(postorder)-1]
        
        root.left = self.buildTree(inorder_left,postorder_left)
        root.right = self.buildTree(inorder_right,postorder_right)
        
        return root

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值