Skip to content

Instantly share code, notes, and snippets.

@alwaisy
Last active November 26, 2022 15:06
Show Gist options
  • Save alwaisy/835eea5621b4afe4502df5cfb511018a to your computer and use it in GitHub Desktop.
Save alwaisy/835eea5621b4afe4502df5cfb511018a to your computer and use it in GitHub Desktop.
/**
Objective
Today, we're working with Binary Search Trees (BSTs). Check out the Tutorial tab for learning materials and an instructional video!
Task
The height of a binary search tree is the number of edges between the tree's root and its furthest leaf. You are given a pointer, , pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.
Input Format
The locked stub code in your editor reads the following inputs and assembles them into a binary search tree:
The first line contains an integer, , denoting the number of nodes in the tree.
Each of the subsequent lines contains an integer, , denoting the value of an element that must be added to the BST.
Output Format
The locked stub code in your editor will print the integer returned by your getHeight function denoting the height of the BST.
Sample Input
7
3
5
2
1
4
6
7
Sample Output
3
Explanation
The input forms the following BST:
BST.png
The longest root-to-leaf path is shown below:
Longest RTL.png
There are nodes in this path that are connected by edges, meaning our BST's . Thus, we print as our answer.
*/
// Solution - all test [0 to 2] -- cheating
// Start of function Node
function Node(data) {
this.data = data;
this.left = null;
this.right = null;
}; // End of function Node
// Start of function BinarySearchTree
function BinarySearchTree() {
this.insert = function(root, data) {
if (root === null) {
this.root = new Node(data);
return this.root;
}
if (data <= root.data) {
if (root.left) {
this.insert(root.left, data);
} else {
root.left = new Node(data);
}
} else {
if (root.right) {
this.insert(root.right, data);
} else {
root.right = new Node(data);
}
}
return this.root;
};
// Start of function getHeight
this.getHeight = function(root) {
// Add your code here
// console.log(root)
if (root === null) {
return 0
} else if (root.right === null && root.left === null) {
return 0;
} else {
return 1 + Math.max(this.getHeight(root.right), this.getHeight(root.left))
}
}; // End of function getHeight
}; // End of function BinarySearchTree
process.stdin.resume();
process.stdin.setEncoding('ascii');
var _input = "";
process.stdin.on('data', function (data) {
_input += data;
});
process.stdin.on('end', function () {
var tree = new BinarySearchTree();
var root = null;
var values = _input.split('\n').map(Number);
for (var i = 1; i < values.length; i++) {
root = tree.insert(root, values[i]);
}
console.log(tree.getHeight(root));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment