Short C++ recursive and iterative solution


  • 0
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int>res;
            /** 
             * Recursive.
             * DFS(root, res);
             * return res; 
             */
            if(!root) return res;
            stack<TreeNode*>s;
            TreeNode* cur(root);
            while(!s.empty() || cur){
                res.push_back(cur->val);
                if(cur->right) s.push(cur->right);
                if(cur->left) cur = cur->left;
                else{
                    if(s.empty()) break;
                    cur = s.top();
                    s.pop();
                }
            }
            return res;
        }
        
        void DFS(TreeNode* root, vector<int>& res){
            if(!root) return;
            res.push_back(root->val);
            DFS(root->left, res);
            DFS(root->right, res);
        }
    

Log in to reply
 

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