本文主要是介绍538. Convert BST to Greater Tree1038. BST to Greater Sum Tree(Leetcode每日一题-2020.09.22),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Problem
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example
Solution
右->中->左 遍历
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:int sum = 0;TreeNode* convertBST(TreeNode* root) {if(!root)return NULL;convertBST(root->right);root->val += sum;sum = root->val;convertBST(root->left);return root;}
};
这篇关于538. Convert BST to Greater Tree1038. BST to Greater Sum Tree(Leetcode每日一题-2020.09.22)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!