JSFiddle - React, Tailwind, and code Playground
JavaScript
var Node = function(name, left, right) {
this.name = name;
this.left = left;
this.right = right;
},
findDeepest = function(node, depth) {
var left, right, depth = depth || 0;
if(typeof node !== 'undefined') {
left = findDeepest(node.left, depth+1);
right = findDeepest(node.right, depth+1);
if(typeof left !== 'undefined' && typeof right !== 'undefined') {
if(left.depth >= right.depth) {
return left;
} else {
return right;
}
} else if(typeof left !== 'undefined') {
return left;
} else if(typeof right !== 'undefined') {
return right;
} else {
return {node: node, depth: depth};
}
}
};
//Now to test it
var deepest = findDeepest(
new Node('A',
/* / \
/ \
/ \
/ \*/
new Node('B'), new Node('C',
/* / \
/ \
/ \
/ \*/
new Node('D'), new Node('E'))));
alert("Found '" + deepest.node.name + "' at depth of "+deepest.depth);
//returns "Found 'D' at depth of 2"