Working with Tree data structures.
Trees are connected graphs with nodes representing an object and edges are lines connecting nodes. Trees are widely used for social networking or in your own computer (the file directories).
trees usually looks like this:
with the topmost node called the root node and it has children, connected by edges/branches. Children can be a node for more children or it can be a leaf node. A leaf node is a node that has no children at all. Knowing a leaf node is very helpful for writing an algorithm for calculating the height.
In order to determine the height, you must add up the max path length + 1, a path is a sequence of nodes (n1, n2... ni).
Writing the height algorithm.
writing the algorithm may sound complicated using recursion so here are some steps:
1) determine the simplest return value. in this case would be if we have a node which is a leaf, return 1. therefore if there is no children return 1.
2) other wise we use recursion to count up the maximum path and add 1 to it. thus the else would look like this:
else:
return max([height(c) for c in t.children]) + 1
## this would go through the children and use them as nodes to count up the height.
This is how to write a recursive code. Its a 2-3 step process.
1) determine the simplest way to return the value and write an if statement about it.
2) figure out the complex way to return the value.
3) write an else statement which would use recursion to go through each item.
(steps 2 and 3 can be merged).
Recursive codes may get complicated you learn about them, but as long as you follow these steps, it would get easier.

No comments:
Post a Comment