Binary Tree
Binary tree is more like a tree with at most two branches per each node. So you can easily implement it with linked list. In the programming, you can just go ahead and make your class with left and right pointer variables or perhaps a structure in c++?
Implementation
Here's an example structure,
struct Node {
int data;
Node* left;
Node* right;
Node(int data) {
this->data = data;
left = NULL;
right = NULL;
}
};To insert elements, we can implement a function which will simply return the instance of the above structure.
Node *insert(Node *root, int data) {
Node *newNode = new Node(data);
if (root == NULL) {
root = newNode;
return root;
}
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node *temp = q.front();
q.pop();
if (temp->left == NULL) {
temp->left = newNode;
return root;
} else {
q.push(temp->left);
}
if (temp->right == NULL) {
temp->right = newNode;
return root;
} else {
q.push(temp->right);
}
}
return root;
}7.1 Preorder Traversal
While traversing, each node has left and right elements, and let's not forget the root. So if we print or process root at first and then left and right node sequentially, that will be our preorder. Things can be a bit tricky if our tree is long. So, we can actually go ahead and use stack for implementing so,
Want even more crazier method? Check this code and laugh later!
Preety kool, right?
7.2 Inorder Traversal
In inorder traversal just like preorder we will visit our fellow members but the difference is that we will visit our root after traversing the lefter one!
And for the recursion, just like before, but print after first call,
7.3 Postorder Traversal
Finally in postorder we will visit our root after we visit it's left and right childrens. Interesting right?
Let's implement in this way,
Please check the text book for understanding the above code. Here we are using pair for storing two characteristics per each stack element. But feel free to use any other method.
Here's an another interesting method, where we can just go ahead and use 2 different stack for storing and organizing our elements,
And finally le'ts not forget recursion, my most favorite (cause it's easy),
And yeah, feel free to try building in your way!
Wrapping up!
Before wrapping lem'me share an another interesting traversing method, that may come handy later, level order traversing,
It's like how we actually build our tree. Kool, right?
Here's the full code, you can go ahead and execute,
Last updated
Was this helpful?