C++ Iterative Solution


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

Log in to reply
 

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