Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

path = 0 # the lenght of the path
    while self.right != None or self.left != None:
        while self.right != None:
            self = self.right
            path = path +1 
        while self.left != None:
            self = self.left
            path = path +1
    return path

this is my sample code for find the Height, is defined as the length of the longest path by number of nodes from self to a leaf. The height of a leaf node is 1.

it doesn't work.

like image 554
Tural Gulmammadov Avatar asked Nov 10 '12 13:11

Tural Gulmammadov


People also ask

How do you find the height of a binary tree using recursion?

To calculate the height of the tree recursively, we need to find the height of it's left subtree and right subtree recursively and add 1 to them (height between the topmost node and its children).

How do you find the height of a binary tree for a node?

Height of a node K (of a Binary Tree) = Number of edges in the longest path connecting K to any leaf node.

How do you find the height of a binary search tree without recursion?

We can use level order traversal to find height without recursion. The idea is to traverse level by level. Whenever move down to a level, increment height by 1 (height is initialized as 0). Count number of nodes at each level, stop traversing when the count of nodes at the next level is 0.

What is the height of a binary tree with n nodes?

If there are n nodes in binary tree, maximum height of the binary tree is n-1 and minimum height is floor(log2n).


1 Answers

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

like image 95
Akash Kandpal Avatar answered Oct 25 '22 10:10

Akash Kandpal