how to find the height of a node in binary tree recursively

痞子三分冷 提交于 2019-12-05 13:07:06

What you're doing isn't recursive, it's iterative. Recursive would be something like:

def height(node):
    if node is None:
        return 0
    else:
        return max(height(node.left), height(node.right)) + 1

You were given the solution by mata, but I suggest you also look at your code and understand what it is doing:

    while self.right != None:
        self = self.right
        path = path +1

What will this do? it will find the right child, then its right child, and so on. So this checks only one path of the "rightmost" leaf.

This does the same for the left:

   while self.left != None:
        self = self.left
        path = path +1

The idea in recursion is that for each subproblem, you solve it using the exact same recipe for all other subproblems. So if you would apply your algorithm only to a subtree or a leaf, it would still work.

Also, a recursive definition calls itself (although you can implement this with a loop, but that is beyond the scope here).

Remeber the definition:

Recursion: see definition of Recursion.

;)

def height(node):
    if node is None:
        return 0
    else:
        if node.left==None and node.right==None:
            return max(height(node.left), height(node.right))+0
        else:
            return max(height(node.left), height(node.right))+1

If you consider each increasing edge to be the height. To pass hackerrank testcases

Here is the complete program in Python ::

class Node :
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def maxDepth(node):
    if node is None :
        return 0
    else :
        ldepth = maxDepth(node.left)
        rdepth = maxDepth(node.right)

        if (ldepth>rdepth):
            return ldepth +1
        else :
            return rdepth +1

root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)


print "Height of tree is %d" %(maxDepth(root))

Source : here

def height(self):
    if self.root !=None:
        return self._height(self.root,0)
    else:
        return 0

def _height(self,cur_node,cur_height):
    if cur_node==None : 
         return cur_height
    left_height = self._height(cur_node.left_child,cur_height+1)
    right_height = self._height(cur_node.right_child,cur_height+1)
    return max(left_height,right_height)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!