# LeetCode #112 路径总和 树 递归

## LeetCode #112 路径总和 树

### 题目描述

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


#### 方法一：递归

# 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(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


©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客