A tree is a representation of the non-linear data structure. A tree can be shown using different user-defined or primitive types of data.
We can use arrays, and classes connected lists or other kinds of data structures to implement the tree. It is a group of interrelated nodes.
Traversing a tree allows us to search for a node, print out the contents of a tree, and much more.
There are two categories of traversals:
Consider the tree:
A
/ \
B C
/ / \
D E F
A, B, D, C, E, F
Notice that you go all the way down one leg before moving on.
and there is three methods for depth first traversal:
Pre-order: root » left » right In-order: left » root » right Post-order: left » right » root
A, B, C, D, E, F
The difference between the two traversal orders lies in the choice of Container.
For depth first use a stack. (The recursive implementation uses the call-stack…) For breadth-first use a queue.
Trees can have any number of children per node, but Binary Trees restrict the number of children to two (hence our left and right children).
K-ary Trees If Nodes are able have more than 2 child nodes, we call the tree that contains them a K-ary Tree. In this type of tree we use K to refer to the maximum number of children that each Node is able to have.
In a BST, nodes are organized in a manner where all values that are smaller than the root are placed to the left, and all values that are larger than the root are placed to the right.
The best way to approach a BST search is with a while loop. ‘ We cycle through the while loop until we hit a leaf, or until we reach a match with what we’re searching for.
Reference Site : Trees