I am trying to get Binary Search Tree`s depth using Node and BinarySearch Tree classes down here
class Node{
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class BinarySearchTree {
constructor() {
this.root = null;
}
insert(data) {
//creating a new node and initialising with data.
const newNode = new Node(data);
if (this.root === null)
this.root = newNode;
else
this.insertNode(this.root, newNode);
}
// Method to insert a node in a tree
// it moves over the tree to find the location
// to insert a node with a given data
insertNode(node, newNode) {
//if the data is less then the node move left
if (newNode.data < node.data) {
if (node.left === null)
node.left = newNode;
else
//Recursively calling function in order to go deeper
this.insertNode(node.left, newNode);
}
//if the data is more than the node move right
else {
if (node.right === null)
node.right = newNode;
else
//if right node not null recursively call the function again in order to go deeper the tree.
this.insertNode(node.right, newNode);
}
}
}
And Run getDepth function in here. I tried to add safeguards to check if tree.right is null or not still I get depthright and depthleft variables as nulls.
function getDepth(tree){
let depthleft = 0, depthright = 0;
if (tree === null){
console.log("TREE " JSON.stringify(tree));
return 0;
}else if (tree["left"] === null && tree["right"] === null ){
return 1;
}else {
depthleft = 1 getDepth(tree["left"]);
depthright = 1 getDepth(tree["right"]);
if (depthright > depthleft){
console.log("DR " depthright);
}else{
console.log("treeleft " JSON.stringify(tree["left"]));
console.log("DllllllllL5 " JSON.stringify(depthleft));
console.log("DlRRRRRRL5 " JSON.stringify(depthright));
}
}
}
function run(arr){
const tree = new BinarySearchTree();
for (const elem of arr){
tree.insert(elem);
}
getDepth(tree.root);
}
run([12,7,19,5,9,10]);
But when I console log depthleft and depthright in getDepth function they become null at some point and it does not work?
Where I am doing wrong?
CodePudding user response:
In the getDepth()
function, you're not returning anything if the node isn't a leaf node. That causes the depth to become null during the traversal. You can fix it by simply returning the correct depth.
function getDepth(tree){
let depthleft = 0, depthright = 0;
if (tree === null) { return 0; }
else if (tree["left"] === null && tree["right"] === null ) { return 1; }
else {
depthleft = 1 getDepth(tree["left"]);
depthright = 1 getDepth(tree["right"]);
return Math.max(depthleft, depthright);
}
}
Running this for your input correctly return 4
.