Print leaf of binary tree

Ujjwal Gupta
1 min readJan 4, 2021

--

A leaf of binary tree doesn’t have any left & right child. We will use this logic to find leaves.

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;
}
}
}
}
}
printLeaves() {
const print = (node) => {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
console.log("leave", node.data);
}
print(node.left);
print(node.right);
}
print(this.root);
}
}
const tree = new BinaryTree();
tree.add(2);
tree.add(1);
tree.add(3);
tree.printLeaves();

--

--

Ujjwal Gupta
Ujjwal Gupta

Written by Ujjwal Gupta

Building starscolab | Ex - Frontend lead Polygon | Creator of jsstore, fortjs | opensource creator | we3, blockchain, solidity | javascript

No responses yet