代码随想录算法训练营第十六天|513.找树左下角的值 112.路径总和 106.从中序与后序遍历序列构造二叉树

513.找树左下角的值

513. 找树左下角的值 - 力扣(LeetCode)

代码随想录

思路:这道题用递归的话,需要把深度每次增加时的第一个值赋值给result。这道题涉及到回溯,因为depth这个参数不会随着递归自动改变

# 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 findBottomLeftValue(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        self.result=None
        self.max_depth=-1
        
        self.findleft(root,0)
        return self.result
    def findleft(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.findleft(cur.left,depth)
            depth-=1
        if cur.right:
            depth+=1
            self.findleft(cur.right,depth)
            depth-=1

而如果直接使用层序遍历的话,就更简单,每一层直接把第一个数来赋值

# 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 findBottomLeftValue(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        if not root:
            return None 
        queue=deque()
        queue.append(root)
        result=None
        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. 113.路径总和

112. 路径总和 - 力扣(LeetCode)

113. 路径总和 II - 力扣(LeetCode)

代码随想录

思路:112只要求找有没有路径,所以递归的返回值应该是bool,所以就是如果找到路径,就返回true,不是叶子节点就递归到两个子节点,有一个能返回true就可以。

# 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):
        """
        :type root: Optional[TreeNode]
        :type targetSum: int
        :rtype: bool
        """
        if not root:
            return False
        pathSum=0
        def search(cur,pathSum):
            if not cur:
                return False
            pathSum+=cur.val
            print(cur.val,pathSum)
            if not cur.left and not cur.right:
                if pathSum==targetSum:
                    return True
            return search(cur.left,pathSum) or search(cur.right,pathSum)
        return search(root,0)
        

113要求给出所有的路径,所以就不需要提供返回值,只需要填充path,如果找到路径就加入result中,注意这里也需要回溯。还需要注意的是path会随时变化,所以添加到result之中的应该是path的拷贝也就是path[:]

# 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 pathSum(self, root, targetSum):
        """
        :type root: Optional[TreeNode]
        :type targetSum: int
        :rtype: List[List[int]]
        """
        result=[]
        path=[]
        def dfs(cur,remain):
            if not cur:
                return 
            remain-=cur.val
            path.append(cur.val)            
            if not cur.left and not cur.right:
                if remain==0:
                    result.append(path[:])                  
                path.pop()
                return
            dfs(cur.left,remain)
            dfs(cur.right,remain)
            path.pop()
            return
        dfs(root,targetSum)        
        return result

106.从中序与后序遍历序列构造二叉树

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

106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

代码随想录

思路:第一次引入了构建二叉树,主要的困难在于如何拆分新的区间,通过前序或者后序确定目前的根节点,再根据中序找到对应的位置,根据这个位置把中序拆分成左右两个区间,而前序或者后序的数组,因为左右子树长度的区间都是一样的,所以根据刚刚获取的两个区间长度来对前序或后序进行拆分。学习了一个找位置的函数是sep_idx=inorder.index(rootval),可以用来找到inorder中第一个值为rootval的位置,括号里还可以设定起始和终点。

# 前序和中序
# 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 buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: Optional[TreeNode]
        """
        if not preorder:
            return None
        rootval=preorder[0]
        root=TreeNode(rootval)
        sep_idx=inorder.index(rootval)
        leftinorder=inorder[:sep_idx]
        rightinorder=inorder[sep_idx+1:]
        size=len(leftinorder)
        leftpreorder=preorder[1:size+1]
        rightpreorder=preorder[size+1:]
        root.left=self.buildTree(leftpreorder,leftinorder)
        root.right=self.buildTree(rightpreorder,rightinorder)
        return root

# 中序和后序
# 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 buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: Optional[TreeNode]
        """
        if not postorder:
            return None
        rootval=postorder[-1]
        root=TreeNode(rootval)
        sep_idx=inorder.index(rootval)
        leftinorder=inorder[:sep_idx]
        rightinorder=inorder[sep_idx+1:]
        size=len(leftinorder)
        leftpostorder=postorder[:size]
        rightpostorder=postorder[size:len(postorder)-1]
        root.left=self.buildTree(leftinorder,leftpostorder)
        root.right=self.buildTree(rightinorder,rightpostorder)
        return root
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值