Contents

leetcode 897

Contents

Leetcode 897, couldn’t get the solution

Leetcode 897

Solution

dfs

/**
 * 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:
    TreeNode* tail;

    TreeNode* increasingBST(TreeNode* root) {
        TreeNode* dummy = new TreeNode(-1);
        tail = dummy;
        dfs(root);
        return dummy->right;
    }

private:
    void dfs(TreeNode* root) {
        if (!root) return;
        dfs(root->left);
        tail->right = root;
        root->left = nullptr;
        tail = root;
        dfs(root->right);
    }
};