Clear C++ solution


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

Log in to reply
 

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