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.
>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