Efficient & easy to understand C++ solution


  • 1
    S

    Use stack to store elements from the tree with Inorder Traversal. Create new treenodes with only right children

    void flatten(TreeNode* root) {
            if(root==NULL){
                return;
            }
            stack<TreeNode*> s;
            if(root->right!=NULL){
                s.push(root->right);
            }
            if(root->left!=NULL){
                s.push(root->left);
            }
            root->left=NULL;
            root->right=NULL;
            TreeNode *next=root;
            while(!s.empty()){
                TreeNode *topNode=s.top();
                TreeNode *temp = new TreeNode(topNode->val);
                next->right=temp;
                next=temp;
                s.pop();
                if(topNode->right!=NULL){
                    s.push(topNode->right);
                }
                if(topNode->left!=NULL){
                    s.push(topNode->left);
                }
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.