The root node in the tree is equal to sum of its all descendants and the leafs are assigned value 0, so if your tree is something like
10
20 30
40 50
output will be
140
0 90
0 0
1. 20 & 30 are left and right child of 10
2. 40 & 50 are left and right child of 30
#include<iostream>
using namespace std;
struct BiTree
{
BiTree* leftNode;
BiTree* rightNode;
int value;
};
void InitBiTree(BiTree *& root)
{
int i;
cin>>i;
if (i!=0)
{
root=new BiTree();
root->value=i;
InitBiTree(root->leftNode);
InitBiTree(root->rightNode);
}
else
{
root=NULL;
}
return;
}
void DisplayTree(BiTree* root)
{
if (root)
{
cout<<root->value<<" ";
DisplayTree(root->leftNode);
DisplayTree(root->rightNode);
}
else
cout<<" "<<"0 ";
}
int SumBiTree(BiTree* &root)
{
if (!root)
{
return 0;
}
int sonsValue=SumBiTree(root->leftNode)+SumBiTree(root->rightNode);
int currentValue=root->value;
root->value=sonsValue;
return (sonsValue+currentValue);
}
int main()
{
BiTree *root;
InitBiTree(root);//叶子节点输入0
DisplayTree(root);
cout<<endl;
SumBiTree(root);
DisplayTree(root);
return 0;
}
10
20 30
40 50
output will be
140
0 90
0 0
1. 20 & 30 are left and right child of 10
2. 40 & 50 are left and right child of 30
#include<iostream>
using namespace std;
struct BiTree
{
BiTree* leftNode;
BiTree* rightNode;
int value;
};
void InitBiTree(BiTree *& root)
{
int i;
cin>>i;
if (i!=0)
{
root=new BiTree();
root->value=i;
InitBiTree(root->leftNode);
InitBiTree(root->rightNode);
}
else
{
root=NULL;
}
return;
}
void DisplayTree(BiTree* root)
{
if (root)
{
cout<<root->value<<" ";
DisplayTree(root->leftNode);
DisplayTree(root->rightNode);
}
else
cout<<" "<<"0 ";
}
int SumBiTree(BiTree* &root)
{
if (!root)
{
return 0;
}
int sonsValue=SumBiTree(root->leftNode)+SumBiTree(root->rightNode);
int currentValue=root->value;
root->value=sonsValue;
return (sonsValue+currentValue);
}
int main()
{
BiTree *root;
InitBiTree(root);//叶子节点输入0
DisplayTree(root);
cout<<endl;
SumBiTree(root);
DisplayTree(root);
return 0;
}