leetcode - 两数之和Ⅳ 输入BST(653)

Posted 神的孩子都在跳舞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode - 两数之和Ⅳ 输入BST(653)相关的知识,希望对你有一定的参考价值。

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

 

解题思路:根据二叉搜索树的特点,对二叉搜索树进行中序遍历可以得到一个从小到达排列的列表,进而将该问题转换为“两数之和Ⅰ”,用双指针或者哈希表求解

因而这题的关键在于,二叉树中序遍历算法。

# 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:
        #先中序遍历 得到一个列表 
        tree_list = []
        def inOrder(root):
            if root == None:
                return None
            inOrder(root.left)
            tree_list.append(root.val)
            inOrder(root.right) 
        inOrder(root)
        #双指针
        i = 0
        j = len(tree_list)-1
        while(i<j):
            if (tree_list[i]+tree_list[j] == k):
                return True
            elif (tree_list[i]+tree_list[j] < k):
                i += 1
            else:
                j -= 1
        return False

 

以上是关于leetcode - 两数之和Ⅳ 输入BST(653)的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode刷题100天—653. 两数之和 IV - 输入 BST( 二叉树)—day35

LeetCode 653 两数之和IV-输入BST[map 二叉树] HERODING的LeetCode之路

⭐算法入门⭐《二叉树 - 二叉搜索树》简单01 —— LeetCode 653. 两数之和 IV - 输入 BST

[LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树

LeetCode 443. 压缩字符串 / 653. 两数之和 IV - 输入 BST / 235. 二叉搜索树的最近公共祖先

653. 两数之和 IV - 输入 BST