Skip to content

Instantly share code, notes, and snippets.

@kolauren
Created January 15, 2013 07:07
Show Gist options
  • Select an option

  • Save kolauren/4536809 to your computer and use it in GitHub Desktop.

Select an option

Save kolauren/4536809 to your computer and use it in GitHub Desktop.
1. Explain what the big three depth-first tree traversals are and what to consider when implementing them.
The big three depth-first tree traversals are ways to traverse a tree. "Depth-first" means that they will traverse to the lowest depth before moving on to the next node. The three ways are inorder (left, root, right), preorder (root, left, right) and postorder (left, right, root).
# 2 .Implement a simple binary (non-search) tree node data structure in your favorite programming language and write the following methods:
# (1) print nodes pre-order, (2) print nodes in-order, (3) print nodes post-order.
class Node:
def __init__(self, left=None, right=None, data=None):
self.left = left
self.right = right
self.data = data
class Tree:
def __init__(self, root):
self.root = root
def preorder(self, node):
if(node):
print node.data
self.preorder(node.left)
self.preorder(node.right)
def inorder(self, node):
if(node):
self.inorder(node.left)
print node.data
self.inorder(node.right)
def postorder(self, node):
if(node):
self.postorder(node.left)
self.postorder(node.right)
print node.data
root = Node(
Node(None, Node(Node(None, None, 29), Node(None, None, 1), 3), 4),
Node(Node(None, None, 45), Node(None, None, 13), 14),
"farts")
tree = Tree(root)
# tree.preorder(root)
# tree.inorder(root)
tree.postorder(root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment