Binary Trees, Binary Search Trees, and K-ary Trees.maximum number of children any node may have in a k-ary tree. In a binary tree, k = 2.one child node, in a binary treeother child node, in a binary treeBinary Tree can have any number of children per node, but Binary Trees restrict the number of children to two (hence our left and right children).
There is no specific sorting order for a binary tree. Nodes can be added into a binary tree wherever space allows.
There are two categories of traversals when it comes to trees:
Depth First
Example:
If we have this sample of tree , the traversals would result in different paths:
A, B, D, E, C, FD, B, E, A, F, CD, E, B, F, C, APre-order
Pre-order means that the root has to be looked at first. When we call preOrder for the first time, the root will be added to the call stack. we start reading our preOrder function’s code from top to bottom. This means that we will output the root.value out to the console.And it will start check the left of the root then when it’s finished it will check the right of the root.
When the root.left and root.right will return null the next node will act as the root to continue execution
Here is the pseudocode for this traversal method:
Here is the pseudocode for this traversal method:
Here is the pseudocode for this traversal method:
The previous tree traversals are similar but the difference between each of the traversals is when you are looking at the
root node.
Breadth First
node-by-node. breadth first traversal uses a queueExample:
Output: A, B, C, D, E, Fadding the root to the queue to fill it the it will dequeue the root and start enqueue the left and right child in that order. then dequeue the front node, enqueue that node’s left and right nodes, and move to the next new front of the queue. And so on until we reach a node that doesn’t have any children, we just dequeue it without any further enqueue.Here is the pseudocode, utilizing a built-in queue to implement a breadth first traversal.
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.Breadth First Traversal
queue, but we are now moving down a list of children of length k, instead of checking for the presence of a left and a right child.Example:
Output: A, B, C, D, E, F, G, Hroot to the queue,then we will dequeue it and now we will start enqueue the childer of the root ,then we will check the front and dequeue it and enqueue it's children , followed by enqueing the current Node’s children continues until our queue is empty of child Nodes.Here is the pseudocode
Binary Search Tree (BST) is a type of tree that does have some structure attached to it. 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.Example:
References:
@By codefellows/Trees