Binary Trees
Binary Trees
Basics A binary tree is a graphical representation of a series of numbers or symbols. They look like this:
There are two parts of the binary tree: children and roots. Roots are further up vertically, and children are further down. In the example above, G is the child of D, and D is the root of G. Most questions will deal with how to traverse a binary tree. Traversing a binary tree just means putting the values of a binary tree in a certain order based on their positions in the tree. Methods of traversal There are three ways to traverse a binary tree: In-order Start at the left most child, move to the root of that child, move to the right child of that root, and continue in that order. In this example, the order would be GDHBEIACFJ Pre-order Start at the highest root, then move to the left child, then the right child. You start with one child, do all of its children, then move on to the next child of the first root. In this example, the order would be ABDGHEICFJ Post-order Start at the left-most child, then the right-most child, then the root. In this example, the order would be GHDIEBJFCA Ex: List the order that the nodes of the tree would be visited in with a post-order traversal
Answer: CBFEGA Ex: What is the order of the nodes visited from an In-order traversal of the following tree?
Computer Science Page 1
Ex: What is the order of the nodes visited from an In-order traversal of the following tree?
Answer: A*B+C Ex: using the figure from the previous problem, what is the order of the nodes visited from a postorder traversal of the tree? Answer: AB*C+ Types of trees There are several types of trees. Here are a few, and how you can identify them. Expression tree - all the nodes (the circles) are expressions (+, -, etc) Min heap - for every node that only has one child, that child must be in the left position (you can't have a node in the right position if its the only child) Search tree - left child must be smaller than the parent node. The right child can be bigger, but the parent cannot. Complete binary tree - every node that has children has two children; no root has only one child.