0 ms c++ simple iterative solution


  • 0
    A
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> a;
        stack<TreeNode*> s;
        vector<int> preorderTraversal(TreeNode* root) {
            if(root == NULL) return a;
            
            go(root);
        
            return a;
        }
        
        // iterative
        void go(TreeNode* t) {
            s.push(t);
            while(1) {
                TreeNode* cur = s.top();
                s.pop();
                a.push_back(cur->val);
                if (cur->right) s.push(cur->right);  
                if (cur->left) s.push(cur->left);
                if (s.empty()) return;
                
            }
        }  
    };
    

Log in to reply
 

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