11.Two Sum IV - Input is a BST
Last updated
Last updated
Given the root
of a Binary Search Tree and a target number k
, return true
if there exist two elements in the BST such that their sum is equal to the given target.
Example 1:
Example 2:
Complexity Analysis
Time complexity : O(n). We need to traverse over the whole tree once in the worst case. Here, n refers to the number of nodes in the given tree.
Space complexity : O(n). The size of the set can grow atmost upto n.
Doing preorder traversal to get an array of sorted order Then Two Sum in a sorted array
Time complexity : O(n). We need to traverse over the whole tree once to do the inorder traversal. Here, n refers to the number of nodes in the given tree.
Space complexity : O(n). The sorted listlist will contain n elements.