solution.cpp 743 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
* /
    class Solution
{
public:
    vector<int> preorderTraversal(TreeNode *root)
    {
        //中前后
        //非递归:栈
        stack<TreeNode *> sta;
        vector<int> ans;
        while (root != NULL || !sta.empty())
        {

            while (root != NULL)
            {
                ans.push_back(root->val);
                sta.push(root);
                root = root->left;
            }
            if (!sta.empty())
            {
                root = sta.top();
                sta.pop();
                root = root->right;
            }
        }
        return ans;
    }
};