代码随想录算法训练营第十八天【二叉树】|513,112,106

513. Find Bottom Left Tree Value

用层序遍历( 迭代法)

# 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

import collections

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

        

112. Path Sum

回溯

向下遍历时从target sum里减去此处的值,如果到叶子节点时计数为0,则返回true,

如果孩子返回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: TreeNode
        :type targetSum: int
        :rtype: bool
        """
        if root == None:
            return False
        return self.traversal(root,targetSum - root.val)
        
    def traversal(self, root, count):
        
        if (root.left == None and root.right == None and count == 0):
            return True
        if (root.left == None and root.right == None and count != 0):
            return False
        if (root.left):
            count -= root.left.val
            if self.traversal(root.left,count):
                return True
            count += root.left.val #回溯向上
        if (root.right):
            count -= root.right.val
            if self.traversal(root.right,count):
                return True
            count += root.right.val #回溯向上
        return False

(略)106. Construct Binary Tree from Inorder and Postorder Traversal 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值