LeetCode简单题之两数之和 IV - 输入 BST
生活随笔
收集整理的這篇文章主要介紹了
LeetCode简单题之两数之和 IV - 输入 BST
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
給定一個二叉搜索樹 root 和一個目標結果 k,如果 BST 中存在兩個元素且它們的和等于給定的目標結果,則返回 true。
示例 1:
輸入: root = [5,3,6,2,4,null,7], k = 9
輸出: true
示例 2:
輸入: root = [5,3,6,2,4,null,7], k = 28
輸出: false
提示:
二叉樹的節點個數的范圍是 [1, 10^4].
-10^4 <= Node.val <= 10 ^4
root 為二叉搜索樹
-10^5 <= k <= 10 ^5
來源:力扣(LeetCode)
解題思路
??一個最簡單的思路:遍歷整棵樹然后逐一檢查是否存在兩個數使得條件成立。
# 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: Optional[TreeNode], k: int) -> bool:temp=set()def inorder(root):if root:inorder(root.left)temp.add(root.val)inorder(root.right)inorder(root)for i in temp: #檢查是否存在另外一個值和i相加等于ktemp.remove(i)if k-i in temp:return Truetemp.add(i)return False
??但是這樣做的話顯然有一個信息是沒有用到的,那就是給定的二叉樹是一個搜索二叉樹。眾所周知搜索二叉樹通過中序遍歷可以生成一個升序的序列,所以如果想要優化的話,那可能需要針對生成的序列進行查找優化了,比如對于當前元素i,檢查是否存在另外一個元素j使得i+j=k,對于i來說如果k-i大于i則在i的后邊尋找,如果k-i<i則在i的左邊尋找,可以使用二分查找也可以使用哈希表。下面以二分查找為例進行優化:
# 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: Optional[TreeNode], k: int) -> bool:temp=[]def inorder(root):if root:inorder(root.left)temp.append(root.val)inorder(root.right)inorder(root)if len(temp)<2:return Falsefor i in range(len(temp)):if k-temp[i]>temp[i]:#如果另一個和數大于當前值,則在其右邊尋找index=bisect.bisect_left(temp,k-temp[i],i+1,len(temp))else:#如果另一個和數小于當前值,則在其左邊尋找index=bisect.bisect_left(temp,k-temp[i],0,i)if len(temp)>index>=0 and temp[index]==k-temp[i] and index!=i:return Trueelse:continuereturn False
總結
以上是生活随笔為你收集整理的LeetCode简单题之两数之和 IV - 输入 BST的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode简单题之汇总区间
- 下一篇: LeetCode简单题之复写零