Saturday, 12 March 2016

Week 8 SLOG - Tree

We spent the last two weeks on trees, specifically generic trees a week ago and binary trees during this week. I'll focus on generic trees this week as its fresh in my mind after working on assignment 2. 

A Tree is an ADT that consists of the root and possibly internal nodes and leafs. The root is the first node in the Tree and the only node without a parent. Each node can be linked to several other nodes which are called its children. In fact, a LinkedList is a type of Tree with only one child. Since a Tree branches out, it naturally lends itself to recursion for traversing the Tree. 

The Tree also can be thought as to contain subtrees as each of its children can have their own children and so on. Some attributes for this are arity, height, path length and depth. The arity is the maximum branching factor of the tree, so the max number of children a node in the tree has. The path length is the number of nodes between a given node and one of its descendants (children, children of children, etc) The height of a tree is 1 + the maximum path length in the tree. The depth is the height of the entire tree minus the height of the given node, which is 0 at the root.

In general for recursive functions of a Tree we do:

def tree_function(tree):
   if not tree.children:
       # Do something since this is a leaf!
   else:
       # This is an internal node
       # Do something
       tree_function(foo) # Do recursion



No comments:

Post a Comment