C++ 中將二叉搜尋樹轉為更大的總和樹
假設我們有一個具有不同值的二叉搜尋樹的根,我們必須修改它,以便每個節點的新值等於原始樹中大於或等於節點值的值之和。我們必須記住我們在處理二叉搜尋樹,並且這應保持二叉搜尋樹的特性。因此,如果輸入樹如下:
則輸出樹如下:
為了解決這個問題,我們將遵循以下步驟:
設定全域性變數:= 0
定義一個遞迴函式 solve(),它將以根作為輸入。
如果根的右子樹不為空,則呼叫 solve(根的右子樹)
全域性變數:= 全域性變數 + 根的值
如果根的左子樹不為空,則呼叫 solve(根的左子樹)
返回根
讓我們看看以下實現以便更好地理解:
示例
#include <bits/stdc++.h> using namespace std; class TreeNode{ public: int val; TreeNode *left, *right; TreeNode(int data){ val = data; left = NULL; right = NULL; } }; void insert(TreeNode **root, int val){ queue<TreeNode*> q; q.push(*root); while(q.size()){ TreeNode *temp = q.front(); q.pop(); if(!temp->left){ if(val != NULL) temp->left = new TreeNode(val); else temp->left = new TreeNode(0); return; }else{ q.push(temp->left); } if(!temp->right){ if(val != NULL) temp->right = new TreeNode(val); else temp->right = new TreeNode(0); return; }else{ q.push(temp->right); } } } TreeNode *make_tree(vector<int> v){ TreeNode *root = new TreeNode(v[0]); for(int i = 1; i<v.size(); i++){ insert(&root, v[i]); } return root; } void tree_level_trav(TreeNode*root){ if (root == NULL) return; cout << "["; queue<TreeNode *> q; TreeNode *curr; q.push(root); q.push(NULL); while (q.size() > 1) { curr = q.front(); q.pop(); if (curr == NULL){ q.push(NULL); } else { if(curr->left) q.push(curr->left); if(curr->right) q.push(curr->right); if(curr == NULL || curr->val == 0){ cout << "null" << ", "; }else{ cout << curr->val << ", "; } } } cout << "]"<<endl; } class Solution { public: int global = 0; TreeNode* bstToGst(TreeNode* root) { if(root->right)bstToGst(root->right); if(root->val != 0) root->val = global = global + root->val; if(root->left)bstToGst(root->left); return root; } }; main(){ vector<int> v = {4,1,6,1,2,5,7,NULL,NULL,NULL,3,NULL,NULL,NULL,8}; TreeNode *root = make_tree(v); Solution ob; tree_level_trav(ob.bstToGst(root)); }
輸入
[4,1,6,1,2,5,7,null,null,null,3,null,null,null,8]
輸出
[30, 36, 21, 37, 35, 26, 15, null, null, null, 33, null, null, null, 8, ]
廣告