题目描述:
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:
Input: The root of a Binary Search Tree like this: 5 / 2 13 Output: The root of a Greater Tree like this: 18 / 20 13
解题思路:
起初的思路时间复杂度不好,借鉴别人的思路,DFS是个更好的方法。
先对右儿子进行处理,对值进行累加,再对父节点进行处理,最后对左儿子进行处理。
代码:
起初的代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* convertBST(TreeNode* root) { 13 if (root == NULL) 14 return NULL; 15 root->right = convertBST(root->right); 16 if (root->right != NULL) 17 root->val = root->val + findLeft(root->right); 18 if (root->left != NULL) { 19 TreeNode* tmp = findR(root->left); 20 tmp->val = tmp->val + root->val; 21 } 22 root->left = convertBST(root->left); 23 /*if (root->left != NULL) 24 root->left->val = root->left->val + root->val;*/ 25 return root; 26 } 27 int findLeft(TreeNode* root) { 28 while (root->left != NULL) { 29 root = root->left; 30 } 31 return root->val; 32 } 33 TreeNode* findR(TreeNode* root) { 34 while (root->right != NULL) { 35 root = root->right; 36 } 37 return root; 38 } 39 };
DFS:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode* convertBST(TreeNode* root) { 13 int sum = 0; 14 DFS(root, sum); 15 return root; 16 } 17 void DFS(TreeNode* root, int& sum) { 18 if (!root) 19 return; 20 DFS(root->right, sum); 21 sum += root->val; 22 root->val = sum; 23 DFS(root->left, sum); 24 } 25 };