C++ Program:
#include<iostream>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* createnode(int x)
{
struct node* new_node=new struct node;
new_node->data=x;
new_node->left=NULL;
new_node->right=NULL;
return new_node;
}
void postorder(struct node* root)
{
if(root)
{
postorder(root->left);
postorder(root->right);
if(root->left)
{
root->data=root->data+root->left->data;
}
if(root->right)
{
root->data=root->data+root->right->data;
}
}
}
int height(struct node* root)
{
if(root==NULL)
{
return 0;
}
else
{
int lheight=1+height(root->left);
int rheight=1+height(root->right);
return lheight>rheight?lheight:rheight;
}
}
void levelorderprint(struct node* root,int level)
{
if(root && level==0)
{
cout<<root->data<<" ";
}
else if(root)
{
levelorderprint(root->left,level-1);
levelorderprint(root->right,level-1);
}
}
void levelorder(struct node* root)
{
int h=height(root);
for(int i=0;i<h;i++)
{
levelorderprint(root,i);
cout<<endl;
}
}
int main()
{
struct node* root1=createnode(1);
root1->left=createnode(2);
root1->right=createnode(3);
root1->left->right=createnode(5);
root1->left->left=createnode(4);
root1->right->right=createnode(7);
root1->right->left=createnode(6);
//root1->right->right->left=createnode(8);
cout<<"The input tree is:\n";
levelorder(root1);
postorder(root1);
cout<<"The sum tree is\n";
levelorder(root1);
}
Output:
The input tree is:
1
2 3
4 5 6 7
The sum tree is
28
11 16
4 5 6 7
Process returned 0 (0x0) execution time : 0.016 s
Press any key to continue.
No comments:
Post a Comment