Find length of binary tree
2 min readJan 4, 2021
Length of binary tree or height of binary tree is maximum no of nodes from root down to leaf nodes.
So if a length at left side or right side is greater with comparision to each other then greater value will be the length.
class Node {
constructor(value) {
this.data = value;
this.left = null;
this.right = null;
}
}class BinaryTree {
add(value) {
const node = new Node(value);
let pointer = this.root;
if (pointer == null) {
this.root = node;
} else {
while (pointer != null) {
if (value < pointer.data) {
if (pointer.left == null) {
pointer.left = node;
pointer = null;
} else {
pointer = pointer.left;
}
} else {
if (pointer.right == null) {
pointer.right = node;
pointer = null;
} else {
pointer = pointer.right;
}
}
}
}
} length() {
let lengthToLeft = 0;
let lengthToRight = 0;
let pointerToLeft = this.root.left;
let pointerToRight = this.root.right;
while (pointerToLeft != null) {
++lengthToLeft;
pointerToLeft = pointerToLeft.left;
}
while (pointerToRight != null) {
++lengthToRight;
pointerToRight = pointerToRight.right;
}
const length = lengthToRight > lengthToLeft ?
lengthToRight : lengthToLeft; // add 1 for the root
return length + 1;
}
}const tree = new BinaryTree();
tree.add(1);
tree.add(2);
tree.add(3);console.log("length", tree.length());