在 C++ 中將二叉搜尋樹轉換為二叉樹,以便將所有大於鍵值之和新增到每個鍵值中。
在該教程中,我們將探討一個程式,該程式將二叉搜尋樹轉換為二叉樹,以便將所有大於鍵值之和新增到每個鍵值中。
為此,我們將使用一個二叉搜尋樹。我們的任務是將該樹轉換為一個二叉樹,並將所有大於鍵值之和新增到當前鍵值中。這將透過逆序排列給定的二叉搜尋樹,並保留所有先前元素之和,最後將其新增到當前元素中來實現。
示例
#include <bits/stdc++.h> using namespace std; //node structure of BST struct node{ int key; struct node* left; struct node* right; }; //creating new node with no child struct node* newNode(int key){ struct node* node = (struct node*)malloc(sizeof(struct node)); node->key = key; node->left = NULL; node->right = NULL; return (node); } //traversing BST in reverse inorder and adding sum void reverse_BST(struct node *root, int *sum_ptr){ if (root == NULL) return; reverse_BST(root->right, sum_ptr); //adding elements along the way *sum_ptr = *sum_ptr + root->key; root->key = *sum_ptr; reverse_BST(root->left, sum_ptr); } //Using sum and updating the values void change_greater(struct node *root){ int sum = 0; reverse_BST(root, &sum); } //printing inorder traversal void printInorder(struct node* node){ if (node == NULL) return; printInorder(node->left); cout << node->key << " " ; printInorder(node->right); } int main(){ node *root = newNode(5); root->left = newNode(2); root->right = newNode(13); cout << "Given Tree :" << endl; printInorder(root); change_greater(root); cout << endl; cout << "Modified Tree :" << endl; printInorder(root); return 0; }
輸出
Given Tree : 2 5 13 Modified Tree : 20 18 13
廣告