題目分析:求dom樹的最大深度
- 以html標簽為根結點;
- 從根節點出發,一層一層找子節點;
- 對於同級節點來說,只需要返回該級子節點返回的最大子節點( node.children )樹。
<!DOCTYPE html>
<html lang="en">
<body>
<div>
<div>
<p>
<span><span></span></span>
</p>
<p></p>
<p><span></span></p>
</div>
</div>
</body>
</html>
<script>
// 求dom樹的最大深度
const getDepth = node => {
if (!node.children || node.children.length === 0) {
return 1
}
const maxChildrenDepth = [...node.children].map(v => getDepth(v))
return 1 + Math.max(...maxChildrenDepth)
}
console.log(getDepth(document.documentElement))
</script>