Accepted C++ solution, 6ms


  • 1
    P
    class Solution {
    public:
        void flatten(TreeNode* root) {
        	TreeNode *currPtr = root;
        	while (currPtr) {
        		if (currPtr->left) {
        			TreeNode *preLast = currPtr->left;
        			while (preLast->left || preLast->right) {
        				if (preLast->right) preLast = preLast->right;
        				else preLast = preLast->left;
        			}
        			preLast->right = currPtr->right;
        			currPtr->right = currPtr->left;
        			currPtr->left = nullptr;
        		}
        		currPtr = currPtr->right;
        	}
        }
    };
    

  • 0
    Q

    Simple iterative solution. Amazing!


Log in to reply
 

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