Binary Tree : Create list of leaves method (Using PYTHON code of LinkedBinaryTre
ID: 3808597 • Letter: B
Question
Binary Tree : Create list of leaves method
(Using PYTHON code of LinkedBinaryTree from : http://bcs.wiley.com/he-bcs/Books?action=chapter&bcsId=8029&itemId=1118290275&chapterId=89002 )
Add the following method to the LinkedBinaryTree class: def leaves list (self) When called on a tree, it will create and return a list, containing the values stored at the leaves of the tree, ordered from left to right. For example, if called on the tree from question 1, it should return [5, 1, 8, 4] Implementation requirement: Your method should run in linear time.Explanation / Answer
Python program to count leaf nodes in Binary Tree
#]]A Binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def getLeafCount(node):
if node is None:
return 0
if(node.left is None and node.right is None):
return 1
else:
return getLeafCount(node.left) + getLeafCount(node.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Leaf count of the tree is %d" %(getLeafCount(root))
This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.