Computer >> Máy Tính >  >> Lập trình >> C ++

Chuyển đổi một cây nhị phân sao cho mọi nút đều lưu trữ tổng của tất cả các nút trong cây con bên phải của nó trong C ++


Trong hướng dẫn này, chúng ta sẽ thảo luận về chương trình chuyển đổi cây nhị phân sao cho mỗi nút lưu trữ tổng của tất cả các nút trong cây con bên phải của nó.

Đối với điều này, chúng ta sẽ được cung cấp một cây nhị phân. Nhiệm vụ của chúng ta là trả về một tầng khác ở đây mỗi nút phải bằng tổng của nút và cây con bên phải của nó.

Ví dụ

#include <bits/stdc++.h>
using namespace std;
//node structure of tree
struct Node {
   int data;
   Node *left, *right;
};
//creation of a new node
struct Node* createNode(int item){
   Node* temp = new Node;
   temp->data = item;
   temp->left = NULL;
   temp->right = NULL;
   return temp;
}
//creating the new binary tree
int rightsum_tree(Node* root){
   if (!root)
      return 0;
   if (root->left == NULL && root->right == NULL)
      return root->data;
   //changing the values of left/right subtree
   int rightsum = rightsum_tree(root->right);
   int leftsum = rightsum_tree(root->left);
   //adding the sum of right subtree
   root->data += rightsum;
   return root->data + leftsum;
}
//traversing tree in inorder pattern
void inorder(struct Node* node){
   if (node == NULL)
      return;
   inorder(node->left);
   cout << node->data << " ";
   inorder(node->right);
}
int main(){
   struct Node* root = NULL;
   root = createNode(1);
   root->left = createNode(2);
   root->right = createNode(3);
   root->left->left = createNode(4);
   root->left->right = createNode(5);
   root->right->right = createNode(6);
   rightsum_tree(root);
   cout << "Updated Binary Tree :\n";
   inorder(root);
   return 0;
}

Đầu ra

Updated Binary Tree :
4 7 5 10 9 6