From 7933941fd37289b37e288e53be5e1b63da1746c5 Mon Sep 17 00:00:00 2001 From: Mohammad S Anwar Date: Thu, 10 Feb 2022 08:00:32 +0000 Subject: - Added guest contributions by Eric Cheung. --- challenge-151/eric-cheung/python/ch-1.py | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100755 challenge-151/eric-cheung/python/ch-1.py (limited to 'challenge-151/eric-cheung/python') diff --git a/challenge-151/eric-cheung/python/ch-1.py b/challenge-151/eric-cheung/python/ch-1.py new file mode 100755 index 0000000000..cab9c88121 --- /dev/null +++ b/challenge-151/eric-cheung/python/ch-1.py @@ -0,0 +1,43 @@ +## Credit: +## https://www.educative.io/edpresso/finding-the-maximum-depth-of-a-binary-tree + +class Node: + def __init__(self , val): + self.value = val + self.left = None + self.right = None + +def maxDepth(root): + ## Null node has 0 depth. + if root == None: + return 0 + + ## Get the depth of the left and right subtree + ## using recursion. + leftDepth = maxDepth(root.left) + rightDepth = maxDepth(root.right) + + ## Choose the larger one and add the root to it. + if leftDepth > rightDepth: + return leftDepth + 1 + else: + return rightDepth + 1 + +## Driver Code + +## Example 1: +## root = Node(1) +## root.left = Node(2) +## root.right = Node(3) +## root.left.left = Node(4) +## root.left.right = Node(5) + +## Example 2: +root = Node(1) +root.left = Node(2) +root.right = Node(3) +root.left.left = Node(4) +root.right.right = Node(5) +root.left.left.right = Node(6) + +print("The max depth is:", maxDepth(root)) \ No newline at end of file -- cgit