LeetCode #112 路径总和 树 递归

LeetCode #112 路径总和 树

题目描述

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22

          5
         / \
        4   8
       /   / \
      11  13  4
     /  \      \
    7    2      1

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。

方法一:递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        if not root : return False

        sum -= root.val
        if(not root.left and not root.right):
            return sum == 0
        return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
  • 时间复杂度: O ( N ) O(N)
  • 空间复杂度:最坏 O ( N ) O(N) ,最好 O ( l o g ( N ) ) O(log(N))

方法二:迭代

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        node_stack = [root]
        sum_stack = [sum]
        while node_stack:
            node = node_stack.pop()
            sum = sum_stack.pop()
            if not node:
                continue
            sum -= node.val
            if sum == 0 and not node.left and not node.right:
                return True
            node_stack.append(node.left)
            node_stack.append(node.right)
            sum_stack.append(sum)
            sum_stack.append(sum)
        return False
发布了67 篇原创文章 · 获赞 2 · 访问量 1368

猜你喜欢

转载自blog.csdn.net/weixin_42511320/article/details/105110401