代码训练营 Day16| 513.找左下角的值 | 112.路径总和 | 106.从中序后序遍历构造二叉树

513.找左下角的值

1. 这题使用层序遍历会比递归要简单很多

2. 因为是要找左下角的值

   1. 层序遍历是使用队列来分别辨别不同层的元素有那些

   2. 最左边的值永远是第一个进入队列的,所以在while的内层循环设置一个判断条件即可获得该值

import collections
# 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: TreeNode
        :rtype: int
        """
        # create queue
        queue = collections.deque([root])

        # makesure the root is not empty
        if root == None:
            return 
        
        # loop until queue is empty
        while queue:
            # record queue size
            size = len(queue)
            # use for loop to get different level elements
            for i in range(size):
                # get first queue elements,and pop it
                cur = queue.popleft()
                
                # when i is 0 that means it's first element in the row, which is left tree value
                if i == 0:
                    result = cur.val
                
                # update left and right child
                if cur.left:
                    queue.append(cur.left)
                if cur.right:
                    queue.append(cur.right)
        
        return result

112.路径总和

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 hasPathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: bool
        """
        # we can use every recursion method, pre,post,middl
        def dfs(node,count):
            # recursion stop condition
            if((node.left == None and node.right == None) and count == 0):
                # it's correct path we want return true
                return True
            
            if(node.left == None and node.right == None and count != 0):
                # since count is not 0, mean's it's wrong path
                return False

            
            # each time recutsion logic

            # left traversal
            # since our recusion stop condtion does not check if node is empty, which when we do the traversal we need to makesure the node is exist
            if(node.left):  
                count -= node.left.val
                # left side recursion
                if(dfs(node.left,count)):
                    # in this case we use false and true to only when node return true we will go throught this path
                    return True
                # back track
                count += node.left.val
            
            # right travseral
            if(node.right):
                count -= node.right.val
                # right recursion
                if(dfs(node.right,count)):
                    return True
                # back track
                count += node.right.val
            
            # if we can't find any return false
            return False

        # makesure is not empty tree
        if root == None:
            return False

        result = dfs(root,targetSum-root.val)
        return result

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

构造二叉树的流程

1. 确定中节点的值很重要

2. 后序遍历的最后一个节点一定是 中间节点,因为后序遍历的顺序是 左右中

3. 因为通过后序遍历找到了中节点,去中序通过中节点来分割,从而得知那个是左区间节点那个是右区间节点,

    因为中序遍历的顺序是: 左中右

4. 通过后序找到中是那个元素,通过中序找到那个是左区间节点和右区间节点

 代码实现分为6步

1. 后序数组为0,空节点

2. 后序数组最后一个元素为节点元素

3. 寻找中序数组的位置作为切割

4. 切中序数组

5. 切后序数组

6. 递归处理左区间右区间

# 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: TreeNode
        """
        
        #第一步:  特殊情况 树为空 递归终止条件
        if not postorder:
            return None

        # 第二步: 后序遍历的最后一个就是当前的中间节点
        root_val = postorder[-1]
        root = TreeNode(root_val)
        
        # 第三步: 寻找切割点
        separator_idx = inorder.index(root_val)

        # 第四步: 切割inorder(中序)数组,得到inorder数组的左,右半边
        inorder_left = inorder[:separator_idx]
        inorder_right = inorder[separator_idx+1:]

        # 第五步: 切割postorder数组. 得到postorder数组的左,右半边.
        # ⭐️ 重点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

你可能感兴趣的:(算法,python,数据结构)