Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<conio.h>
- using namespace std;
- typedef struct node
- {
- int data;
- node *left,*right;
- };
- typedef node* tree;
- void Init(tree &root)
- {
- root=NULL;
- }
- void TraverseNLR(tree root)
- {
- if(root!=NULL)
- {
- cout<<root->data<<"\t";
- TraverseNLR(root->left);
- TraverseNLR(root->right);
- }
- }
- void TraverseLNR(tree root)
- {
- if(root!=NULL)
- {
- TraverseNLR(root->left);
- cout<<root->data<<"\t";
- TraverseNLR(root->right);
- }
- }
- void TraverseLRN(tree root)
- {
- if(root!=NULL)
- {
- TraverseNLR(root->left);
- TraverseNLR(root->right);
- cout<<root->data<<"\t";
- }
- }
- int InsertTree( tree & root,int x)
- {
- if(root!=NULL)
- {
- if(root->data==x)
- return 0;
- if(root->data>x)
- return InsertTree(root->left,x);
- else
- return InsertTree(root->right,x);
- }
- else
- {
- root =new node;
- if(root==NULL)
- return -1;
- root->data=x;
- root->left=root->right=NULL;
- return 1;
- }
- }
- void CreateTree(tree &root)
- {
- int x,n,t;
- cout<<"Nhap vao so node:";
- cin>>n;
- for(int i=1;i<=n;i++)
- {
- cout<<"Node thu ["<<i<<"]=";
- cin>>x;
- t=InsertTree(root,x);
- if(t==0)
- {
- cout<<"node co roi !";
- i--;
- }
- else if(t==-1)
- {
- cout<<"Bo nho day !";
- getch();
- exit(1);
- }
- }
- }
- void RemoveTree(tree &root)
- {
- if(root!=NULL)
- {
- RemoveTree(root->left);
- RemoveTree(root->right);
- delete root;
- }
- }
- int demnodeco1caycon(tree root)
- {
- if(root==NULL)
- return 0;
- if((root->left==NULL && root->right!=NULL)||(root->left!=NULL && root->right==NULL))
- return 1+demnodeco1caycon(root->left)+demnodeco1caycon(root->right);
- return 1;
- }
- int tonggiatrinode1caycon(tree root)
- {
- if(root==NULL)
- return 0;
- if((root->left==NULL && root->right!=NULL)||(root->left!=NULL && root->right==NULL))
- return root->data+tonggiatrinode1caycon(root->right)+tonggiatrinode1caycon(root->left);
- return tonggiatrinode1caycon(root->right)+tonggiatrinode1caycon(root->left);
- }
- void main()
- {
- int x;
- int dem=0;
- int dem2=0;
- tree root;
- Init(root);
- CreateTree(root);
- cout<<"Cay theo NLR:";
- TraverseNLR(root);
- cout<<"\nCay theo LNR:";
- TraverseLNR(root);
- cout<<"\nCay theo LRN:";
- TraverseLRN(root);
- //RemoveTree(root);
- int t=demnodeco1caycon(root);
- cout<<"\nCo tat ca "<<t<<" node co 1 cay con";
- cout<<"\nTong gia tri node co 1 cay con la:"<<tonggiatrinode1caycon(root);
- getch();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement