Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
3
Indexable
Never
/**
 * 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:
/* we take the root and solve its LEFT and RIGHT parts , then we wtich it back properly first by setting root->left= NULL and then we set root->right=LEFT;
then we go to the end of right of updated root and attach orininal RIGHT there */


    void flatten(TreeNode* root) { //recursion
        if(root==NULL) return;
        TreeNode* left =root->left;
        TreeNode* right=root->right;
        
        root->left=NULL;

        flatten(left);
        flatten(right);
        root->right=left;
        TreeNode* tmp=root;
        while(tmp->right!=NULL) tmp=tmp->right;
        tmp->right=right;
    }
};


/* 
class Solution {
public:
    void flatten(TreeNode* root) { //pre order travrsal
        TreeNode* curr=root;
        while(curr!=NULL){
            if(curr->left!=NULL){
                TreeNode* pred=curr->left;
                while(pred->right!=NULL){
                    pred =pred->right;
                }
                pred->right= curr->right;
                curr->right=curr->left;
                curr->left=NULL;
            }
            curr=curr->right;
        }
    }
}; */