Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <set>
- #include <stdio.h>
- using namespace std;
- //create the tree, display elements, using the inorder bypass, do exercise, then display new tree
- struct tree{
- int inf;
- tree *left;
- tree *right;
- tree *par;
- };
- tree *node(int x){
- tree *n = new tree;
- n->inf = x;
- n->left = NULL;
- n->right = NULL;
- n->par = NULL;
- return n;
- }
- void insert(tree *&tr, int x){//only elements with different values
- tree* n = node(x);
- if(!tr) tr = n;
- else{
- tree* y = tr;
- while(y){
- if(n->inf > y->inf)
- if(y->right)
- y = y->right;
- else{
- n->par = y;
- y->right = n;
- break;
- }
- else
- if(n->inf < y->inf)
- if(y->left)
- y = y->left;
- else{
- n->par = y;
- y->left = n;
- break;
- }
- else break;
- }
- }
- }
- void inorder(tree *tr){
- if(tr){
- inorder(tr->left);
- cout << tr->inf << " ";
- inorder(tr->right);
- }
- }
- void for_sum(tree *tr, int &sum){
- if(tr){
- for_sum(tr->left, sum);
- sum += tr->inf;
- for_sum(tr->right, sum);
- }
- }
- int main()
- {
- #ifdef _DEBUG
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- #endif
- //count the sum of nodes
- int n;
- cin >> n;
- tree* Tree = NULL;
- cout << n << endl;
- for(int i = 0; i < n; i++){
- int cur; cin >> cur;
- insert(Tree, cur);
- }
- inorder(Tree);
- int res = 0;
- for_sum(Tree, res);
- cout << "Sum of nodes is " << res << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement