美文网首页
1038. Binary Search Tree to Grea

1038. Binary Search Tree to Grea

作者: 是嘤嘤嘤呀 | 来源:发表于2020-04-02 19:33 被阅读0次
image.png

解题思路:从右往左遍历(右->根->左),需要一个全局变量缓存整个右半部分的值
代码

/**
 * 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 sums = 0;
    void selution(TreeNode* root) {
        if (root == NULL) return;
        selution(root -> right);
        sums += root -> val;
        root -> val = sums;
        selution(root->left);
    }
    TreeNode* bstToGst(TreeNode* root) {
        selution(root);
        return root;
    }
};

相关文章

网友评论

      本文标题:1038. Binary Search Tree to Grea

      本文链接:https://www.haomeiwen.com/subject/wfjfphtx.html