Wednesday, April 12, 2017

count number of leaf nodes

Python 3 solution:

class Node():
    def __init__(self, data, left=None , right=None):
        self.data = data
        self.left = left
        self.right = right
   
    def countLeafNode(self):
        node = self
        stack = []
        stack.append(node)
        count = 0
        while len(stack):
            node = stack.pop()
            if node.left is None and node.right is None:
                count += 1
            else:
                stack.append(node.right)
                stack.append(node.left)
        return count

if __name__ == "__main__":
    # make tree
    root = Node(1)
    root.left= Node(2)
    root.left.left = Node(4)
    root.left.right = Node(5)
    root.right = Node(3)
    root.right.left = Node(5)
    root.right.right = Node(7)
    print(root.countLeafNode())
   
    

No comments:

Post a Comment