c++ recursive & iterative solutions


  • 0
    B

    iterative

        vector<int> result;
        stack<TreeNode *> s;
        
        void pushleft(TreeNode *root){
            if(!root) return ;
            
            TreeNode *p=root;
            while(p){
                result.push_back(p->val);
                if(p->right) s.push(p->right);
                p=p->left;
            }
            
            return ;
        }
        
        vector<int> preorderTraversal(TreeNode* root) {
            pushleft(root);
            
            while(!s.empty()){
                TreeNode *t=s.top();
                s.pop();
                pushleft(t);
            }
            
            return result;
        }
    

    recursive

        vector<int> result;
    
        void dfs(TreeNode *root){
            if(!root) return ;
            
            result.push_back(root->val);
            dfs(root->left);
            dfs(root->right);
            
            return ;
        }
        
        vector<int> preorderTraversal(TreeNode* root) {
            dfs(root);
            
            return result;
        }
    
    

Log in to reply
 

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