Problem Statement
Given the root of a binary tree, return a deepest node.
For example, in the following tree, return d.
a
/ \
b c
/
d
My Implementation
module.exports = {
deepestNode: function deepestNode(node, level) {
if (!level)
level = 0;
node.depth = level;
if (!node.left && !node.right)
return node;
let deepestLeft, deepestRight = node;
if (node.left)
deepestLeft = deepestNode(node.left, level + 1);
if (node.right)
deepestRight = deepestNode(node.right, level + 1);
if (deepestLeft.depth > deepestRight.depth)
return deepestLeft;
else
return deepestRight;
},
TreeNode: (val) => {
return {
val: val,
left: null,
right: null
}
}
};
Test Class
const expect = require('chai').expect;
const deepestNode = require('../../src/google/deepestNode');
let a = deepestNode.TreeNode('a');
let b = deepestNode.TreeNode('b');
let c = deepestNode.TreeNode('c');
let d = deepestNode.TreeNode('d');
a.left = b;
b.left = d;
a.right = c;
expect(deepestNode.deepestNode(a).val).eq('d');
a = deepestNode.TreeNode('a');
expect(deepestNode.deepestNode(a).val).eq('a');
I am a Javascript newbie so any comments regarding either the algorithm itself or the use of Javascript is welcome.