[LeetCode] 538.Convert BST to Greater Tree
- 题目描述
- 解题思路
- 实验代码
题目描述
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
解题思路
这道题依然是要用递归的方法。想要解决这道题首先要对二叉搜索树作一个了解。二叉搜索树的特点是:若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值。知道这个特点以后这道题就得到了简化和理解。左子节点加上它父节点和右兄弟的值,父节点加上右子节点的值。这道题就得到了解决。
实验代码
/**
* 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;
void travel(TreeNode* root) {
if (!root) return;
if (root->right)
travel(root->right);
sum += root->val;
root->val = sum;
if (root->left)
travel(root->left);
}
TreeNode* convertBST(TreeNode* root) {
travel(root);
return root;
}
};
本文介绍了一种将二叉搜索树(BST)转换为Greater Tree的方法,即每个节点的值等于原值加上所有大于该值的节点之和。通过递归地遍历二叉树并利用二叉搜索树特性实现这一目标。
1594

被折叠的 条评论
为什么被折叠?



