LeetCode538: Convert BST to Greater Tree 把二叉搜索树转换为累加树

LeetCode538: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

分析

直接看到题目会想到利用中序遍历,进行累加,得到最终的总和后,再利用中序遍历进行减去前面节点的和赋值给当前节点的运算,这样也可以得到最终的结果。最后参考别人的代码时,知道了可以对中序遍历进行逆操作,也即是左根右变为右根左
写非递归算法时,注意中序遍历要利用栈来存储~

代码

// 递归版本
// class Solution {
// public:
//     int node = 0;
//     TreeNode* convertBST(TreeNode* root) {
//         if(!root) return NULL;
//         convertBST(root->right);
//         root->val += node;
//         node = root->val;
//         convertBST(root->left);
//         return root;
//     }
    
// };
// 非递归版本
class Solution {
public:
    int node = 0;
    TreeNode* convertBST(TreeNode* root) {
        if(!root) return NULL;
        stack<TreeNode*> tr;
        TreeNode *p = root;
        //检查栈是否为空,以及栈中p指针是否有指向
        while( !tr.empty() || p ) {
            //先右遍历到最右节点,先将根存入栈,再存右孩子,弹出元素时实现先右节点后根的遍历
            while(p) {
                tr.push(p);
                p = p->right;
            }
            //将指针移到栈头
            p = tr.top();
            //已经赋值给p,将栈头元素弹出
            tr.pop();
            //执行操作
            p->val += node;
            node = p->val;
            p = p->left;
        }
        //由于p是指向root的指针,因此对p所做的操作会改变root,最后直接返回root
        return root;
    }
    
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值