../ Competitive Programming
-rw-r--r--aguang994 B1 min read

Leet Code Daily 2024-06-25 - Binary Search Tree to Greater Sum Tree

Solution

BFS

Code

c++
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    int dfs(TreeNode* root, int d) {
        if (root == nullptr) {
            return 0;
        }
        int val = root->val;
        int sum_right = dfs(root->right, d);
        int sum_left = dfs(root->left, val + sum_right + d);
        root->val += sum_right + d;
        return sum_left + val + sum_right;
    }

    TreeNode* bstToGst(TreeNode* root) {
        dfs(root, 0);
        return root;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window