Easy Iterative 0 ms C++ Solution


  • 0
    Y
    class Solution {
    public:
        vector<int> preorderTraversal(TreeNode* root) {
            vector<int> ans;
            
            if(root == NULL) return ans;
            stack<TreeNode*> treeStack;
            
            while(1) {
                if(root != NULL) {
                    ans.push_back(root->val);
                    if(root->right != NULL) treeStack.push(root->right);
                    root = root->left;
                } else {
                    if(treeStack.size() == 0) break;
                    else {
                        root = treeStack.top();
                        treeStack.pop();
                    }
                }
            }
            return ans;
        }
    };

Log in to reply
 

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