I have written a blog about the tree data structure overview. If you don’t know about tree data structure, click here to see my blog.
In this blog, we will be going to know about Binary Tree. I hope you will get some idea of it.
A binary tree is a type of tree. But there is some condition. To be a binary tree, it has to fulfill some requirements. Otherwise, it will not be considered a binary tree.
We all know about the node. And in a binary tree, each node has at most two children. It’s okay to have two children, one child, or even no children. But if a node contains more than two children, or you can say it two child nodes, the tree will not be considered a binary tree. As a node has at most two children, we can refer to those children as the left child and right child.
Let’s see an example to get a better idea of it.
Root / \ Left Child Right Child
Example 1 Example 2 Example 3 Example 4 3 7 1 1 / \ / \ / \ / \ 4 9 5 6 2 3 2 3 / \ / \ / | \ \ \ 1 2 5 7 1 2 3 4 4 Binary Tree Not a Binary Tree Binary Tree Binary Tree Example 5 Example 6 Example 7 0 3 9 / / | \ / | \ \ 1 1 7 2 2 3 4 5 Binary Tree Not a Binary Tree Not a Binary Tree
In our above examples, three of them are not binary trees.
In examples 2 and 3, both have a node with three children. And the last example has four children. As these trees have at least a node with more than two children, we can’t count them as binary trees.
I hope you got the idea about Tree and Binary Tree. All binary tree is a tree, but all tree is not binary tree.
There are mainly two types of algorithms for traversing. Traversing means visiting nodes in a binary tree. These are:
- DFS (Depth First Search)
- Preorder Traversal
- Inorder Traversal
- Postorder Traversal
- BFS (Breadth First Search)
- Level Order Traversal
These follows different rule for traversing in a binary tree. I will cover details about these traversing algorithms in a different blog in the near future. If you know these algorithms, it helps you to manipulate data in a binary tree.