Skip to content

Commit

Permalink
feat: Add function to get DOM tree height recursively and iteratively
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaban-Eissa committed Jun 7, 2024
1 parent 0074c14 commit 148ed0f
Showing 1 changed file with 107 additions and 0 deletions.
107 changes: 107 additions & 0 deletions 58.get-DOM-tree-height.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# 58. get DOM tree height

### Problem

https://bigfrontend.dev/problem/get-DOM-tree-height

#

### Problem Description

Height of a tree is the maximum depth from root node. Empty root node have a height of 0.

If given DOM tree, can you create a function to get the height of it?

For the DOM tree below, we have a height of 4.

```html
<div>
<div>
<p>
<button>Hello</button>
</p>
</div>
<p>
<span>World!</span>
</p>
</div>
```

Can you solve this both recursively and iteratively?

#

### Recursive Solution with DFS

```js
/**
* @param {HTMLElement | null} tree
* @return {number}
*/
function getHeight(tree) {
if (tree === null) {
return 0;
}
return 1 + Math.max(getTreeHeight(tree.left), getTreeHeight(tree.right));
}
```

#

### Iterative Solution using Stack

```js
/**
* @param {HTMLElement | null} tree
* @return {number}
*/
function getHeight(tree) {
if (tree === null) {
return 0;
}

let maxHeight = 0;
const stack = [[tree, 1]];

while (stack.length > 0) {
const [el, height] = stack.pop();
maxHeight = Math.max(height, maxHeight);

for (const child of el.children) {
stack.push([child, height + 1]);
}
}

return maxHeight;
}
```

#

### Iterative Solution with BFS

```js
/**
* @param {HTMLElement | null} tree
* @return {number}
*/
function getHeight(tree) {
if (tree === null) {
return 0;
}

let maxHeight = 0;
const queue = [[tree, 1]];

while (queue.length > 0) {
const [el, height] = queue.shift();
maxHeight = Math.max(height, maxHeight);

for (const child of el.children) {
queue.push([child, height + 1]);
}
}

return maxHeight;
}
```

0 comments on commit 148ed0f

Please sign in to comment.