Easy to understand C++ using a Vector and Recursion


  • 0
    C
    class Solution 
    {
    public: 
        void flatten(TreeNode* root) 
        {
            if (root == NULL)
            {
                return;
            }
            vector<TreeNode*> myQueue;
            TreeNode *temp1 = root, *temp2;
            queueAll(root, myQueue);
            for (int i = 1; i < myQueue.size(); i++)
            {
                temp2 = myQueue[i];
                temp1->right = temp2;
                temp1->left = NULL;
                temp1 = temp2;
            }
            temp1->right = NULL;
            temp1->left = NULL;
        }
        
        void queueAll(TreeNode* subRoot, vector<TreeNode*>& myQueue)
        {
            if (subRoot == NULL)
            {
                return;
            }
            myQueue.push_back(subRoot);
            queueAll(subRoot->left, myQueue);
            queueAll(subRoot->right, myQueue);
        }
    };

Log in to reply
 

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