Short and Simple Iterative Solution in C++ (4ms)


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

Log in to reply
 

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