538. / 1038. 把二叉搜索树转换为累加树
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree
著作权归领扣网络所有。
给出二叉 搜索 树的根节点,该树的节点值各不相同,请你将其转换为累加树(Greater Sum Tree),使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。
提醒一下,二叉搜索树满足下列约束条件:
节点的左子树仅包含键 小于 节点键的节点。
节点的右子树仅包含键 大于 节点键的节点。
左右子树也必须是二叉搜索树。
方法1:反中序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void inorder(struct TreeNode* root, int *sum) {
if (root) {
inorder(root->right, sum);
*sum += root->val;
root->val = *sum;
inorder(root->left, sum);
}
}
struct TreeNode* bstToGst(struct TreeNode* root){
int sum = 0;
inorder(root, &sum);
return root;
}
方法2:Morris遍历(线索树遍历)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* convertBST(struct TreeNode* root){
int sum = 0;
struct TreeNode* p = NULL, *head = root;
while (root) {
if (root->right) {
// p 节点就是当前 root 节点向左走一步,然后一直向右走至无法走为止
p = root->right;
while (p->left && p->left != root) {
p = p->left;
}
if (p->left == NULL) { //让 p 的右指针指向 root,继续遍历左子树
p->left = root;
root = root->right;
} else { // 说明左子树已经访问完了,我们需要断开链接
sum += root->val;
root->val = sum;
p->left = NULL;
root = root->left;
}
} else { //如果没有左孩子,则直接访问右孩子
sum += root->val;
root->val = sum;
root = root->left;
}
}
return head;
}