The task is to create a function to determine the height of a DOM tree.
The boilerplate code
function getHeight(tree) {
// your code here
}
If the tree is null or undefined, there is no node
if(!tree) {
return 0;
}
If the tree has no children, it is a leaf. A leaf node has a height of 1
if(!tree.children || tree.children.length === 0) {
return 1;
}
Recursively, calculate the height of each child. Keep track of the maximum height
let maxChildHeight = 0;
for(const child of tree.children) {
maxChildHeight = Math.max(maxChildHeight, getHeight(child));
}
The final code
function getHeight(tree) {
// your code here
if(!tree) {
return 0;
}
if(!tree.children || tree.children.length === 0) {
return 1;
}
let maxChildHeight = 0;
for(const child of tree.children) {
maxChildHeight = Math.max(maxChildHeight, getHeight(child));
}
return maxChildHeight + 1;
}
That's all folks!
Top comments (0)