C++ solution using stack


  • 0
    W
    vector<int> preorderTraversal(TreeNode* root) {
            if(root==NULL) return vector<int>();
            
            stack<TreeNode*> st; st.push(root);
            vector<int> ans;
            
            while(!st.empty()){
                TreeNode* tp=st.top();
                ans.push_back(tp->val);
                st.pop();
                if(tp->right) st.push(tp->right);
                if(tp->left) st.push(tp->left);
            }
            
            return ans;
        }

Log in to reply
 

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