538. Convert BST to Greater Tree 發表於 2023-02-13 | 分類於 leetcode problemsolution123456789101112131415161718192021222324252627282930/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */class Solution {public: void inorder(TreeNode* root, int &val){ if(!root) return ; inorder(root->right, val); val+=root->val; root->val = val; inorder(root->left, val); } TreeNode* convertBST(TreeNode* root) { int val = 0; inorder(root, val); return root; }}; 12345678910111213class Solution {public: int cur =0; TreeNode* convertBST(TreeNode* root) { if(!root) return root; convertBST(root->right); cur+=root->val; root->val = cur; convertBST(root->left); return root; }};