Data Structure Binary Tree: Convert an arbitrary Binary Tree to a tree that holds Children Sum Property

时间:2021-08-10 06:23:11

http://www.geeksforgeeks.org/convert-an-arbitrary-binary-tree-to-a-tree-that-holds-children-sum-property/

 #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std; struct node {
int data;
struct node *left, *right;
node() : data(), left(NULL), right(NULL) { }
node(int d) : data(d), left(NULL), right(NULL) { }
}; void print(node *node) {
if (!node) return;
print(node->left);
cout << node->data << " ";
print(node->right);
} void _convert(node* root, int diff) {
if (!root) return;
if (root->left) {
root->left->data += diff;
_convert(root->left, diff);
}
else if (root->right) {
root->right->data += diff;
_convert(root->right, diff);
}
} void convert(node* root) {
if (!root || !root->left && !root->right) return;
convert(root->left);
convert(root->right);
int sum = ;
sum += root->left? root->left->data : ;
sum += root->right? root->right->data : ;
if (sum >= root->data) root->data = sum;
else _convert(root, root->data - sum);
} int main() {
struct node* root = new node();
root->left = new node();
root->right = new node();
root->left->left = new node();
root->left->right = new node();
root->right->left = new node();
root->right->right = new node();
print(root);
cout << endl;
convert(root);
print(root);
return ;
}