Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // program to print the boundary traversal of a binary tree
- #include <iostream>
- #include <queue>
- #include <map>
- using namespace std;
- // node class
- class node{
- public:
- int data;
- node* left;
- node* right;
- };
- // function that returns a pointer to new node
- node* createNode(int element){
- node* temp = (node*) malloc(sizeof(node));
- temp->data = element;
- temp->left = NULL;
- temp->right = NULL;
- return temp;
- }
- // function to print the left boundary of the tree
- void print_left_boundary(node* root){
- if (root != NULL){
- if (root->left != NULL){
- cout<<root->data<<" ";
- print_left_boundary(root->left);
- }else if (root->right != NULL){
- cout<<root->data<<" ";
- print_left_boundary(root->right);
- }
- }
- return;
- }
- // function to print the right boundary of the tree
- void print_right_boundary(node* root){
- if (root != NULL){
- if (root->right != NULL){
- print_right_boundary(root->right);
- cout<<root->data<<" ";
- }else if (root->left != NULL){
- print_right_boundary(root->left);
- cout<<root->data<<" ";
- }
- }
- return;
- }
- // function to print the leaves of a binary tree
- void print_leaves(node* root){
- if (root != NULL){
- print_leaves(root->left);
- if(root->left == NULL && root->right == NULL){
- cout<<root->data<<" ";
- }
- print_leaves(root->right);
- }
- }
- void boundary_traversal(node* root){
- print_left_boundary(root);
- print_leaves(root);
- print_right_boundary(root);
- return;
- }
- int main() {
- node* head = createNode(1);
- head->left = createNode(2);
- head->right = createNode(3);
- head->left->left = createNode(4);
- head->left->right = createNode(5);
- head->right->right = createNode(6);
- head->left->left->right = createNode(7);
- head->right->right->left = createNode(8);
- head->left->left->right->left = createNode(9);
- head->left->left->right->left->left = createNode(10);
- head->right->right->left->right = createNode(11);
- cout<<"Boundary traversal of the binary tree is : "<<endl;
- boundary_traversal(head);
- return 0;
- }
- /*
- Boundary traversal of the binary tree is :
- 1 2 4 7 9 10 5 11 8 6 3 1
- Process finished with exit code 0
- */
Add Comment
Please, Sign In to add comment