Hello!
I'm having problems with finding the depth of a node in a binary tree, I have implemented some code:
// node -> root
depth(number, node=this.root) {
let queue = [];
let depth = 0;
queue.push(node)
while(queue.length > 0) {
const current = queue.shift()
// first we check the node's value
if (current.value === number) {
return depth;
}
// and we continue traversing
if(current.left !== null) {
queue.push(current.left)
}
if(current.right !== null) {
queue.push(current.right)
}
if(current.right !== null || current.left !== null) {
depth++ // if there's more branches with nodes, add to the counter
}
}
}
I'm using breadth-first-search to perform this action.
This is my tree right now.
│ ┌── 6345
│ │ └── 324
│ │ └── 69
│ ┌── 67
│ │ │ ┌── 65
│ │ └── 64
│ │ └── 62
│ ┌── 23
│ │ │ ┌── 9
│ │ └── 8
│ ┌── 7
│ │ │ ┌── 5
│ │ └── 4
│ │ └── 3
└── 2
└── 1
And when I run this function:
console.log(newTree.depth(67)) // 5 - false, should be 4
console.log(newTree.depth(1)) // 1 - that's right
console.log(newTree.depth(5)) // 4 - also right
console.log(newTree.depth(69)) // 9 - that's even more than the maximum depth