Created
April 17, 2022 22:03
-
-
Save MohammedALREAI/2c132f1f6dfa5efe182032c079691dec to your computer and use it in GitHub Desktop.
find Closest Value In Bs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NodeClass{ | |
value:number = 0; | |
left:NodeClass|null = null; | |
right:NodeClass|null = null; | |
constructor() | |
{ | |
this.value = 0; | |
this.left = null; | |
this.right = null; | |
} | |
}; | |
// Utility function to create a new Node | |
function newNode(data:number) | |
{ | |
var temp = new NodeClass(); | |
temp.value = data; | |
temp.left = temp.right = null; | |
return temp; | |
} | |
function findClosestValueInBstHelper(tree:NodeClass, target:number,closest:number):number{ | |
if (tree === null) return closest; | |
if (Math.abs(target - closest) > Math.abs(target - tree.value)) { | |
closest = tree.value; | |
} | |
if (target < tree.value && tree.left) { | |
return findClosestValueInBstHelper(tree.left, target, closest); | |
} else if (target > tree.value && tree.right) { | |
return findClosestValueInBstHelper(tree.right, target, closest); | |
} else { | |
return closest; | |
} | |
} | |
function findClosestValueInBst(tree:NodeClass, target:number,close:number=Infinity){ | |
return findClosestValueInBstHelper(tree, target, Infinity); | |
} | |
function findClosestValueInBstHelperIterative(tree:NodeClass, target:number,closest:number=Infinity):number{ | |
let currentNode = tree; | |
while (currentNode !== null) { | |
if (Math.abs(target - closest) > Math.abs(target - currentNode.value)){ | |
closest = currentNode.value; | |
} | |
if (target < currentNode.value && currentNode.left) { | |
currentNode = currentNode.left; | |
} else if (target > currentNode.value && currentNode.right) { | |
currentNode = currentNode.right; | |
} else { | |
break; | |
} | |
} | |
return closest; | |
} | |
// Driver Code | |
/* Constructed binary tree is | |
5 | |
/ \ | |
3 9 | |
/ \ / \ | |
1 2 8 12 */ | |
var root = newNode(5); | |
root.left = newNode(3); | |
root.right = newNode(9); | |
root.left.left = newNode(1); | |
root.left.right = newNode(2); | |
root.right.left = newNode(8); | |
root.right.right = newNode(12); | |
console.log(findClosestValueInBstHelperIterative(root,7)) | |
console.log(findClosestValueInBstHelperIterative(root,7)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment