C++ iterative solution


  • 0
    T
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
    	    TreeNode* p = root;
    	    vector<int> v;
    	    stack<TreeNode*> s;
    
    	    if (p == NULL) {
    		    return v;
    	    }
    
    	    while (!s.empty() || p) {
    		    if (p) {
    			    s.push(p);
    			    v.push_back(p->val);
    			    p = p->left;
    		    }
    		    else {
    			    p = s.top();
    			    s.pop();
    			    p = p->right;
    		    }
    	    }
    
    	    return v;
        }
    };

Log in to reply
 

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