[leetcode] 538. Convert BST to Greater Tree

来源:互联网 发布:家居网络推广招聘 编辑:程序博客网 时间:2024/05/16 19:42

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     13Output: The root of a Greater Tree like this:             18            /   \          20     13

这道题是“转化”二叉树,题目难度为Medium。

如果题目变为:将所有节点值转化为当前值加上比它小的节点值,相信会简单很多。我们知道中序遍历BST时节点值呈递增状态,所有比当前节点值小的节点在中序遍历时都在它之前,因此通过中序遍历即可顺利“转化”二叉树。

题目要求将所有节点值转化为当前值加上比它大的节点值,在中序遍历时只需要先遍历节点的右子树即可。具体代码:

class Solution {    void inOrder(TreeNode* n, int& curSum) {        if(n->right) inOrder(n->right, curSum);        curSum += n->val;        n->val = curSum;        if(n->left) inOrder(n->left, curSum);    }public:    TreeNode* convertBST(TreeNode* root) {        if(!root) return NULL;        int curSum = 0;        inOrder(root, curSum);        return root;    }};

0 0