Skip to content

Commit 7bb3553

Browse files
committed
Max depth of a DOM tree
1 parent 95639e7 commit 7bb3553

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

challenges/DOM.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
3. [Design and Implement a Node Store, which supports DOM element as key](#Q3)
1010
4. [Implement a function to find the closest ancestor with the provided selector](#Q4)
1111
5. [Write a function to find the corresponding node in two identical DOM trees](#Q5)
12+
6. [Write a function to get depth of a given DOM tree](#Q6)
1213

1314
---
1415

@@ -168,4 +169,41 @@ const findCorrespondingNode = (rootA, rootB, target) => {
168169

169170
<br />
170171

172+
173+
#### Q6
174+
### Write a function to get depth of a given DOM tree
175+
176+
- A depth of a given DOM tree is the max depth till which DOM nodes are nested
177+
178+
179+
```js
180+
/**
181+
* @param {HTMLElement | null} tree
182+
* @return {number}
183+
*/
184+
function getHeight (root) {
185+
if(!root) return 0;
186+
187+
let maxDepth = 0;
188+
189+
const helper = (current, depth = 1) => {
190+
if(current.hasChildNodes()) {
191+
for(let child of current.children) {
192+
helper(child, depth + 1);
193+
}
194+
}
195+
maxDepth = Math.max(maxDepth, depth)
196+
}
197+
198+
helper(root)
199+
return maxDepth
200+
}
201+
```
202+
203+
###### References
204+
- https://web.dev/dom-size/
205+
- https://bigfrontend.dev/problem/get-DOM-tree-height
206+
207+
<br />
208+
171209
[[] Back to top](#home)

0 commit comments

Comments
 (0)