LeetCode 538. Convert BST to Greater Tree (C++)

来源:互联网 发布:win10网络共享速度慢 编辑:程序博客网 时间:2024/04/28 19:55

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

思路:变种的中序遍历,从右往左遍历。代码如下:

/** * 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:    TreeNode* convertBST(TreeNode* root) {        int toadd = 0;        dfs(root, toadd);        return root;    }    void dfs (TreeNode* root, int& toadd){        if (!root) return;                dfs(root->right,toadd);        root->val += toadd;        toadd = root->val;        dfs(root->left,toadd);    }};


原创粉丝点击