Meta / Amazon / Google / Microsoft| Trim a Binary Search Tree | LeetCode-669: Medium | JavaScript Implementation
We will be seeing the solution to the LeetCode problem 669 in JavaScript. I hope you will find it useful.
Problem Statement:
Given the root
of a binary search tree and the lowest and highest boundaries as low
and high
, trim the tree so that all its elements lies in [low, high]
. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a unique answer.
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds
Link to Problem: https://leetcode.com/problems/trim-a-binary-search-tree/
JavaScript Implementation:
var trimBST = function(root, low, high) {
const util = (node)=>{
if(!node) return null;
node.left = util(node.left)
node.right = util(node.right)
if(node.val < low) return node.right
if(node.val > high) return node.left
return node
}
root = util(root)
return root
};
Thank you for reading hope this code is helpful to you.