From 148ed0f38157d4e977a55fdb639efd2cc495db3e Mon Sep 17 00:00:00 2001 From: Shaban-Eissa Date: Fri, 7 Jun 2024 14:59:24 +0300 Subject: [PATCH] feat: Add function to get DOM tree height recursively and iteratively --- 58.get-DOM-tree-height.md | 107 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 58.get-DOM-tree-height.md diff --git a/58.get-DOM-tree-height.md b/58.get-DOM-tree-height.md new file mode 100644 index 0000000..0f5f831 --- /dev/null +++ b/58.get-DOM-tree-height.md @@ -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 +
+
+

+ +

+
+

+ World! +

+
+``` + +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; +} +```