title: How to get leaf nodes of a tree using Python?
body: <p>Hi there I am new to OOP so have this in mind while you are reading this.</p>
  
  <p>I have a simple Python tree implementation(see below code). </p>
  
  <pre><code>class TreeNode(object):
      def __init__(self, data):
          self.data = data
          self.children = []
  
      def add_child(self, obj):
          self.children.append(obj)
  
  class Tree:
      def __init__(self):
          self.root = TreeNode('ROOT')
  
      def preorder_trav(self, node):
          if node is not None:
              print node.data
              if len(node.children) == 0:
                  print "("+ node.data + ")"
                  for n in node.children:
                      self.preorder_trav(n)
  
  if __name__ == '__main__':
      tr = Tree()
      n1 = tr.root
      n2 = TreeNode("B")
      n3 = TreeNode("C")
      n4 = TreeNode("D")
      n5 = TreeNode("E")
      n6 = TreeNode("F")
  
      n1.add_child(n2)
      n1.add_child(n3)
      n2.add_child(n4)
      n2.add_child(n5)
      n3.add_child(n6)
  
      tr.preorder_trav(n1)
  </code></pre>
  
  <p>What I need now is to implement a method for getting Leaf Nodes back. By the term <strong>leaf node</strong> I mean a node that has no children. </p>
  
  <p>I am wondering how to make a <strong>get_leaf_nodes()</strong> method.</p>
  
  <p>Some solutions come to my mind are </p>
  
  <ol>
  <li>Making a <code>self.leaf_nodes = []</code> inside the <code>__init__</code> method. By making this I know it will be seen only by this tree instance. </li>
  <li>Making a class member  <code>leaf_nodes = []</code>  above <code>__init__</code> method. By making this I know all tree instances will be able to see leaf_nodes list.</li>
  </ol>
  
  <p>The above solutions will cause me to create a leaf_nodes list inside my class so the <code>get_leaf_nodes()</code> method could use. What I am looking for is to only have a <code>get_leaf_nodes()</code> method that will do the computation on my tree and will return a list. </p>
  
  <p>For example in C we would call <code>malloc()</code> and then we could return the pointer to the function that called the <code>get_leaf_nodes()</code>.</p>