// https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

// Given the root of a binary tree, flatten the tree into a "linked list":

////////////////////////////////////////////////////////////////////////////////

// post-order traversal: [right left root]
// record prevRight, set root->right = prevRight, root->left = nullptr
//   1         1      1
//  / \   ->  /   ->   \
// 2   3     2          2
//            \          \
//             3          3
/**
 * 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 {
private:
    TreeNode* prevRight = nullptr;
public:
    void flatten(TreeNode* root) {
        if (!root) return;
        flatten(root->right);
        flatten(root->left);
        root->right = prevRight;
        root->left = nullptr;
        prevRight = root;
    }
};
