將二叉樹轉換成每節點中儲存其所有右子樹中節點的和的二叉樹
在本教程中,我們將探討如何將一個二叉樹轉換為每個節點都儲存其右子樹中所有節點的和的二叉樹。
為此,我們將提供一棵二叉樹。我們的任務是返回另一棵樹,其中每個節點必須等於節點及其右子樹的和。
示例
#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