A 0ms C++ Solution Using Wikipedia Method


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

Log in to reply
 

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