將滿二叉樹轉換爲求和樹
給滿出二叉樹,編寫算法將其轉化爲求和樹
什麼是求和樹:二叉樹的求和樹, 是一顆同樣結構的二叉樹,其樹中的每個節點將包含原始樹中的左子樹和右子樹的和。
二叉樹:
10
/
-2 6
/ \ / \
8 -4 7 5
求和樹:
20(4-2+12+6)
/
4(8-4) 12(7+5)
/ \ / \
0 0 0 0
二叉樹給出前序和中序輸入,求和樹要求中序輸出;
所有處理數據不會大於int;
輸入描述:
2行整數,第1行表示二叉樹的前序遍歷,第2行表示二叉樹的中序遍歷,以空格分割
輸出描述:
1行整數,表示求和樹的中序遍歷,以空格分割
示例1
輸入
10 -2 8 -4 6 7 5
8 -2 -4 10 7 6 5
輸出
0 4 0 20 0 12 0
思路:
1.按照先序和中序去構建出二叉樹
可參考https://blog.csdn.net/yunzhongguwu005/article/details/9270085
2.遞歸更新各節點的sum值
#include "iostream"
#include "vector"
#include "string"
#include "sstream"
#include "math.h"
#include "algorithm"
using namespace std;
struct node
{
struct node* left = NULL;
struct node* right = NULL;
int data = 0;
int sum = 0;
};
node* build_tree(int* pre, int* mid,int len)
{
int a = 0,b = 0;
int index = 0;
if (len <= 0)
return NULL;
node* root = new node;
root->data = *pre;
for (int i = 0; i < len; i++)
{
if (mid[i] == *pre)
{
index = i;
break;
}
}
root->left = build_tree(pre + 1, mid, index);
root->right = build_tree(pre + index + 1, mid + index + 1, len - index - 1);
return root;
}
//遞歸更新二叉樹節點的sum值
void add(node* root)
{
if (root->left == NULL || root->right == NULL)
{
root->sum = 0;
return;
}
add(root->left);
add(root->right);
if (root->left != NULL && root->right != NULL)
{
root->sum = root->left->sum + root->left->data + root->right->data + root->right->sum;//左右節點的值加上左右節點的sum值
}
}
void inorder_display(node* root)
{
if (root != NULL)
{
inorder_display(root->left);
cout << root->sum << " ";
inorder_display(root->right);
}
}
int main()
{
vector<int> vpre, vmid;
string spre, smid;
int a = 0;
while (getline(cin, spre))
{
getline(cin, smid);
istringstream is1(spre);
while (is1 >> a)
{
vpre.push_back(a);
}
istringstream is2(smid);
while (is2 >> a)
{
vmid.push_back(a);
}
int* pre = new int[vpre.size()];
int* mid = new int[vmid.size()];
for (int i = 0; i < vpre.size(); i++)
{
pre[i] = vpre[i];
mid[i] = vmid[i];
}
//node* root = build_tree(pre,mid,7);
node* root = build_tree(pre, mid, vpre.size());
add(root);
//root->data = root->left->data + root->right->data;
inorder_display(root);
cout << endl;
}
}