Posted on

Description

Submission

/**
 * 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:
    void flatten(TreeNode* root) {
        if(root == nullptr) return;
        if(!root->left) {
            flatten(root->right);
            return;
        }

        TreeNode* h1 = root->left;
        TreeNode* h2 = root->right;

        flatten(root->left);
        flatten(root->right);
        
        while(h1->right) {
            h1 = h1->right;
        }
        h1->right = h2;
        
        root->right = root->left;
        root->left = nullptr;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *