Tuesday, October 18, 2022
HomeWordPress DevelopmentTwo Sum IV - Enter is a BST

Two Sum IV – Enter is a BST


Given the foundation of a Binary Search Tree and a goal quantity okay, return true if there exist two components within the BST such that their sum is the same as the given goal.

Instance 1:
Enter: root = [5,3,6,2,4,null,7], okay = 9
Output: true

Instance 2:
Enter: root = [5,3,6,2,4,null,7], okay = 28
Output: false

Strategy 1 : Descriptive & straightforward to grasp

/**
 * Definition for a binary tree node.
 * operate TreeNode(val, left, proper) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.proper = (proper===undefined ? null : proper)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {quantity} okay
 * @return {boolean}
 */
var findTarget = operate (root, okay) {
  // accumulating all Ingredient type BST
  let allElements = [];
  // inorder traversal becoz it is going to give sorted array for simplicity
  operate inOrderTraversal(root) {
    if (root === null) {
      return null;
    }
    inOrderTraversal(root.left);
    allElements.push(root.val);
    inOrderTraversal(root.proper);
  }
  inOrderTraversal(root);
  // creating map to maintain observe of all components
  let map = new Map();
  allElements.forEach((ingredient, index) => {
    map.set(ingredient, index);
  });
  // primary loop to examine if two values from array can provide up the required sum
  for (let i = 0; i < allElements.size; i++) {
    let num = allElements[i];
    let diff = okay - num;
    // checking if diff exist in map & additionally we've to ensure
    // index of present ingredient just isn't similar as of matching ingredient
    if (map.has(diff) && map.get(diff) !== i) {
      return true;
    }
  }
  return false;
};

Enter fullscreen mode

Exit fullscreen mode

Strategy 2 : Modified the above answer to do it in O(N)

/**
 * Definition for a binary tree node.
 * operate TreeNode(val, left, proper) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.proper = (proper===undefined ? null : proper)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {quantity} okay
 * @return {boolean}
 */
var findTarget = operate(root, okay) {
     let map= new Map();
    let bool=false;

    const inorder =(root)=>{
        if(root===null) return;
        inorder(root.left);
        if(map.has(okay-root.val)){
            bool=true;
        }else{
            map.set(root.val);
        }
        inorder(root.proper);  
    }
   inorder(root);
   return bool;
};
Enter fullscreen mode

Exit fullscreen mode

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments