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.
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).
Height of a node K (of a Binary Tree) = Number of edges in the longest path connecting K to any leaf node.
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.
If there are n nodes in binary tree, maximum height of the binary tree is n-1 and minimum height is floor(log2n).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With