653. 两数之和 IV - 输入 BST

给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。

案例 1:

输入:
5
/ \
3 6
/ \ \
2 4 7

Target = 9

输出: True
 

案例 2:

输入:
5
/ \
3 6
/ \ \
2 4 7

Target = 28

输出: False

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum-iv-input-is-a-bst

二叉树前序遍历+双指针

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findTarget(self, root: TreeNode, k: int) -> bool:
        def preorderTraversal(root):
            if not root:return []
            stack, res = [root], []
            while stack:
                root = stack.pop()
                if root:
                    res.append(root.val)
                    if root.right:
                        stack.append(root.right)
                    if root.left:
                        stack.append(root.left)
            return res
        node=preorderTraversal(root)
        n=len(node)
        if n<2:return False
        l=0
        r=n-1
        node.sort()
        while l<r:
            sum=node[l]+node[r]
            if sum<k:l+=1
            if sum>k:r-=1
            if sum==k:return True
        return False

 

 dfs

class Solution:
    def findTarget(self, root, k):
        visited = set()
        return self.dfs(root, k, visited)
    
    def dfs(self, root, k, visited):
        if not root:
            return False
        if k - root.val in visited:
            return True
        visited.add(root.val)
        return self.dfs(root.left, k, visited) or self.dfs(root.right, k, visited)

 

posted @ 2020-10-05 14:23  XXXSANS  阅读(138)  评论(0编辑  收藏  举报