#include <bits/stdc++.h>
using namespace std;
// tree node is defined
class TreeNode
{
public:
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int data)
{
val = data;
left = NULL;
right = NULL;
}
};
void preorder(TreeNode *root)
{
// base case
if (root == NULL)
return;
stack<TreeNode *> st;
st.push(root);
while (!st.empty())
{
TreeNode *cur = st.top();
st.pop();
// traverse current node first
cout << cur->val << " ";
// put right subtree first
if (cur->right)
st.push(cur->right);
// put left subtree then as it will
// stay in top for next iteration
if (cur->left)
st.push(cur->left);
}
}
int main()
{
// building the tree
TreeNode *t = new TreeNode(7);
t->left = new TreeNode(1);
t->left->left = new TreeNode(0);
t->left->right = new TreeNode(3);
t->left->right->left = new TreeNode(2);
t->left->right->right = new TreeNode(5);
t->left->right->right->left = new TreeNode(4);
t->left->right->right->right = new TreeNode(6);
t->right = new TreeNode(9);
t->right->left = new TreeNode(8);
t->right->right = new TreeNode(10);
printf("Preorder traversal of the above tree is:\n");
preorder(t);
return 0;
}
Output
reorder traversal of the above tree is:
7 1 0 3 2 5 4 6 9 8 10
0 Comments