代码随想录 Day18

513.找树左下角的值

深度优先搜索(DFS)的方式来遍历二叉树,同时维护了最大深度和最左边叶子节点的值。

递归法+回溯

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        self.max_depth = float('-inf')
        self.result = None
        self.tarvle(root, 0)
        return self.result
    def tarvle(self,cur,depth):
        if not cur.left and not cur.right:
            if depth>self.max_depth:
                self.max_depth=depth
                self.result=cur.val
            return
        if cur.left:
            depth+=1
            self.tarvle(cur.left,depth)
            depth-=1
        if cur.right:
            depth+=1
            self.tarvle(cur.right,depth)
            depth-=1

递归法+回溯(精简版)

class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        self.max_depth = float('-inf')
        self.result = None
        self.traversal(root, 0)
        return self.result
    def traversal(self, node, depth):
        if not node.left and not node.right:
            if depth > self.max_depth:
                self.max_depth = depth
                self.result = node.val
            return        
        if node.left:
            self.traversal(node.left, depth+1)
        if node.right:
            self.traversal(node.right, depth+1)

(深度 depth 在不同层次之间增加和减少,以确保我们正确地跟踪节点所在的深度,而不会受到递归调用的深度影响。这种方式帮助我们在二叉树中正确导航并执行递归遍历。)

迭代方法(优先)

from collections import deque
class Solution:
    def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue=collections.deque([root])
        result=[]
        while queue:
            size=len(queue)
            for i in range(size):
                cur=queue.popleft()
                if i==0:
                    result=cur.val
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
        return result

112. 路径总和

递归法

#         self.right = right
class Solution:
    def tarevel(self,cur,count):
        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.tarevel(cur.left,count):
                return True
            count+=cur.left.val
        if cur.right:
            count-=cur.right.val
            if self.tarevel(cur.right,count):
                return True
            count+=cur.right.val
        return False  
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        if not root:
            return False
        return self.tarevel(root,targetSum- root.val)

迭代先跳了

112. 路径总和II

class Solution:
    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[:])
            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()

        return

    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        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.从中序与后序遍历序列构造二叉树

递归

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

105.从前序与中序遍历序列构造二叉树

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder:
            return None
        root_val=preorder[0]
        root=TreeNode(root_val)
        part_idx=inorder.index(root_val)
        inorder_left = inorder[:part_idx]
        inorder_right = inorder[part_idx + 1:]
        preorder_left = preorder[1:1 + len(inorder_left)]
        preorder_right = preorder[1 + len(inorder_left):]

        root.left=self.buildTree(preorder_left,inorder_left)
        root.right=self.buildTree(preorder_right,inorder_right)
        return root
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值