Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.47 KB | None | 0 0
  1. //Given an arbitrary binary tree, convert it to a binary tree that holds
  2. //Children Sum Property. You can only increment data values in any node
  3. //(You cannot change structure of tree and cannot decrement value of any node).
  4. // 50
  5. // / \
  6. // / \
  7. // 7 2
  8. // / \ /\
  9. // / \ / \
  10. // 3 5 1 30
  11.  
  12. #include<iostream>
  13. using namespace std;
  14.  
  15. class tree
  16. {
  17. public:
  18. int data;
  19. class tree* left;
  20. class tree* right;
  21. tree(int data)
  22. {
  23. this->data = data;
  24. left = NULL;
  25. right = NULL;
  26. }
  27. };
  28.  
  29. void insert(class tree** root, int data)
  30. {
  31. if(!*root)
  32. {
  33. *root = new tree(data);
  34. return;
  35. }
  36. else if((*root)->data > data)
  37. insert(&(*root)->left, data);
  38. else
  39. insert(&(*root)->right, data);
  40. }
  41.  
  42. void traverseUpToDown(class tree* root)
  43. {
  44. if(!root || (!root->left && !root->right))
  45. return;
  46. int diff = 0;
  47. diff = root->data - (((root->left)?(root->left->data):0) + ((root->right)?(root->right->data):0));
  48.  
  49. if(diff > 0)
  50. {
  51. if(root->left)
  52. root->left->data += diff;
  53. else
  54. root->right->data += diff;
  55. }
  56. traverseUpToDown(root->left);
  57. traverseUpToDown(root->right);
  58. }
  59.  
  60. void traverseDownToUp(class tree* root)
  61. {
  62. if(!root || (!root->left && !root->right))
  63. return;
  64. traverseDownToUp(root->left);
  65. traverseDownToUp(root->right);
  66. int diff = 0;
  67. diff = root->data - (((root->left)?(root->left->data):0) + ((root->right)?(root->right->data):0));
  68. if(diff < 0)
  69. root->data += -1*diff;
  70. }
  71.  
  72. void convertToChildrenSumProperty(class tree* root) // will be doing two traversals
  73. {
  74. traverseDownToUp(root); //first convert to required property from bottom up manner.
  75. traverseUpToDown(root); // now from top to bottom.
  76. }
  77.  
  78. void display(class tree* root)
  79. {
  80. if(root)
  81. {
  82. display(root->left);
  83. cout<<" "<<root->data;
  84. display(root->right);
  85. }
  86. }
  87.  
  88. int main()
  89. {
  90.  
  91. class tree* root = new tree(50);
  92. root->left = new tree(7);
  93. root->right = new tree(2);
  94. root->left->left = new tree(3);
  95. root->left->right = new tree(5);
  96. root->right->left = new tree(1);
  97. root->right->right = new tree(30);
  98.  
  99. display(root);
  100. cout<<endl;
  101.  
  102. convertToChildrenSumProperty(root);
  103. display(root);
  104. cout<<endl;
  105.  
  106. system("PAUSE");
  107. return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement