Another way to solve this problem iteratively (0ms)


  • 1
    Z
    class Solution {
    public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        TreeNode *arr[10000];
        int top = -1;
        TreeNode *p = root;
        while(p)
        {
            while(p)
            {
                res.push_back(p->val);
                arr[++top] = p;
                p = p->left;
            }
        
            while(p == NULL && top >= 0)
            {
                p = arr[top];
                p = p->right;
                top--;
            }
        }
        return res;
    }
    

    };


Log in to reply
 

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