From 86d533c4bf8ac9e1a54e9e3abf4c7d557386eeda Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com> Date: Thu, 3 Aug 2023 17:04:33 -0700 Subject: [PATCH] Create trie_find_height.py --- tries/trie_find_height.py | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 tries/trie_find_height.py diff --git a/tries/trie_find_height.py b/tries/trie_find_height.py new file mode 100644 index 0000000..c37410f --- /dev/null +++ b/tries/trie_find_height.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# author: bt3gl + + +class Node: + + def __init__(self, val=None, children=None): + self.val = val + self.children = children + + +def max_depth_recursive(root): + + if root is None: + return 0 + + if root.children == []: + return 1 + + height = [max_depth_recursive(c) for c in root.children] + return max(height) + 1 + + +def max_depth_iterative(root): + + stack = [] + if root is not None: + stack.append((1, root)) + + depth = 0 + + while stack != []: + + this_depth, node = stack.pop() + if node is not None: + depth = max(depth, this_depth) + for c in node.children: + stack.append((this_depth + 1, c)) + + return depth