Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding the maximum height of left and right subtree

I would like to implement the following function:

    def get_height(root, d):
        
        if root.left:
            left = get_height(root.left, d + 1)
        if root.right:
            right = get_height(root.right, d + 1)
        

The idea is simple: For a given node, I want the maximum height of its left and right subtree. The code is not finished yet obviously. I am looking for a clean way to finish the code above, so the return value is the max. height of the left and right subtree.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To just complete the method, you need to add a return and ensure that the base case works. The base case is when the node is a leaf. So you need to give default values for left and right:

def get_height(root, d):
    left = d
    right = d
    if root.left:
        left = get_height(root.left, d + 1)
    if root.right:
        right = get_height(root.right, d + 1)
    return max(left, right)

This is however not the best practice. You should avoid the extra d parameter. You can do without, and let each call return the height of that node, without having to know anything about the parent. When the recursive call is made, the caller can add 1 to the returned value:

def get_height(root):
    left = 0
    right = 0
    if root.left:
        left = get_height(root.left) + 1
    if root.right:
        right = get_height(root.right) + 1
    return max(left, right)

You can also move the base case one step further, so only one if is needed:

def get_height(root):
    if not root:
        return -1
    return max(get_height(root.left), get_height(root.right)) + 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading