DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 100

The task is to create a function to determine the height of a DOM tree.

The boilerplate code

function getHeight(tree) {
  // your code here         
}
Enter fullscreen mode Exit fullscreen mode

If the tree is null or undefined, there is no node

if(!tree) {
 return 0;
}
Enter fullscreen mode Exit fullscreen mode

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;
  }
Enter fullscreen mode Exit fullscreen mode

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));
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)