题目:
题目链接:https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst/
解题思路:
类似两数之和的解题思路
添加一个hash表保存已经遍历过的数字,只是需要将遍历方式修改为树的遍历方式
代码实现:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findTarget(self, root: TreeNode, k: int) -> bool:
if not root:
return False
rec = set()
stack = [root]
while stack:
node = stack[-1]
stack.pop()
other_num = k - node.val
if other_num in rec:
return True
rec.add(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return False