question archive python question: define a function min_depth_leaf, which takes a Tree instance and returns the minimum depth of a leaf in the tree
Subject:Computer SciencePrice:3.86 Bought8
python question:
define a function min_depth_leaf, which takes a Tree instance and returns the minimum depth of a leaf in the tree. In other words, it returns the minimum length of a path from the root to a leaf.
# Tree node class Node: def __init__(self , key): self.data = key self.left = None self.right = None # the required function def min_depth_leaf(root): # Corner Case.Should never be hit unless the code is # called on root = NULL if root is None: return 0 # Base Case : Leaf node.This acoounts for height = 1 if root.left is None and root.right is None: return 1 # If left subtree is Null, recur for right subtree if root.left is None: return min_depth_leaf(root.right)+1 # If right subtree is Null , recur for left subtree if root.right is None: return min_depth_leaf(root.left) +1 return min(min_depth_leaf(root.left), min_depth_leaf(root.right))+1 # Driver Program root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print ('Minimum depth is: ',min_depth_leaf(root))
Please see the attached file for the complete solution