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; } };