1、题目描述
2、问题分析
使用一个vector将所有节点的值以升序排列。然后比较,求和,加上。
3、代码
1 TreeNode* convertBST(TreeNode* root) { 2 if (root == NULL) 3 return NULL; 4 5 vector<int> v; 6 inorder(root,v); 7 increaseVal(root, v); 8 9 return root; 10 11 } 12 13 void increaseVal(TreeNode *root, vector<int> &v) 14 { 15 if(root == NULL) 16 return ; 17 int sum = 0; 18 auto it = find(v.begin(), v.end(), root->val); 19 if (it != v.end() - 1) { 20 sum = accumulate(it + 1, v.end(), 0); 21 root->val = root->val + sum; 22 } 23 24 increaseVal(root->left, v); 25 increaseVal(root->right, v); 26 } 27 28 void inorder(TreeNode *root, vector<int> &v) 29 { 30 if (root == NULL) 31 return ; 32 inorder(root->left, v); 33 v.push_back(root->val); 34 inorder(root->right,v); 35 }