-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add function to get DOM tree height recursively and iteratively
- Loading branch information
1 parent
0074c14
commit 148ed0f
Showing
1 changed file
with
107 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
``` |