C++ simple solution using stack


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

Log in to reply
 

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