#include<iostream> #include<vector> #include<stack> using namespace std; struct TreeNode // 定义树节点的结构 { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; /* class Solution // 中序遍历二叉树,迭代解法 { public: vector<int> result; vector<int> preorderTraversal(TreeNode* root) // 中序遍历二叉树,返回的是数组 { if (root == nullptr) { return {}; } preorderTraversal(root->left); result.push_back(root->val); preorderTraversal(root->right); return result; } }; */ class Solution //递归解法 { public: vector<int> preorderTraversal(TreeNode* root) { stack<TreeNode*> sta; vector<int> result; if (root == nullptr) { return {}; } TreeNode* cur = root; while (cur != nullptr || !sta.empty()) { if (cur != nullptr) { sta.push(cur); cur = cur->left; } else { cur = sta.top(); sta.pop(); result.push_back(cur->val); cur = cur->right; } } return result; } }; int main() { TreeNode* node1 = new TreeNode(1); TreeNode* node2 = new TreeNode(2); TreeNode* node3 = new TreeNode(3); node1->right = node2; node2->left = node3; TreeNode* root = node1; vector<int> res; Solution solution; res = solution.preorderTraversal(root); vector<int>::iterator iter = res.begin(); while (iter != res.end()) { cout << *iter << endl; iter++; } return 0; }