The in-class exercises on pre-order, in-order, post-order traversals again require the recursive way of thinking. Any given tree is made of 3 elements, the root, left subtree, and the right subtree. The root is a value, and the subtrees are either empty or represent values that are also the parent nodes for its children.
In pre-order Binary trees, the path goes from root, left subtree, and right subtree. And in in-order, the path goes from left subtree, root, and right subtree. So the first element in the preorder will always be the root of the tree. In in-order traversal, because the root in the middle, the elements before the root belong to the left subtree, and the elements after the root belong the right subtree. Using the same method, we can also divide the elements in the preorder list to the two branches, and recursively solving the parent nodes and its children nodes in two branches to complete reconstructing the tree. Also, there are exceptions when the subtree we construct has none or only one element (e.g. leaf nodes), and this special case has to be coded under a if/else condition.
No comments:
Post a Comment