Two Sum IV - 입력이 BST임
Example 1:
Input: root = [5,3,6,2,4,null,7], k = 9
Output: true
접근하다
This question is similar to finding if their are two elements in an array such that their sum is equal to the given target.
This problem can be solved either using BFS or DFS. We will solve this using level order traversal(BFS) which uses queue data structure for tree traversing.
The idea here is initialize an empty set , for every node check if target-node.value is available in set , if it is available return True , else add that node value to the set.
At the end directly return False as there is no such elements present in BST.
The reason why I have chosen set for storing the node values is , insert and retrieve operations on set can be done in O(1) time complexity as internally set is implemented using Hashing.
암호
from collections import deque
# 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:
queue = deque()
queue.append(root)
available = set()
while len(queue)>0:
popped = queue.popleft()
if k-popped.val in available:
return True
else:
available.add(popped.val)
if popped.left:
queue.append(popped.left)
if popped.right:
queue.append(popped.right)
return False
Note: If anyone want to more about level order traversal of a tree , please let me know in comments. I will write a detailed post on level order traversal.
Reference
이 문제에 관하여(Two Sum IV - 입력이 BST임), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/dheerajthodupunoori/two-sum-iv-input-is-a-bst-484l텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)