将二叉树转换成每节点中存储其所有右子树中节点的和的二叉树
在本教程中,我们将探讨如何将一个二叉树转换为每个节点都存储其右子树中所有节点的和的二叉树。
为此,我们将提供一棵二叉树。我们的任务是返回另一棵树,其中每个节点必须等于节点及其右子树的和。
示例
#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;
}输出
Updated Binary Tree : 4 7 5 10 9 6
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP