#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 {}; } result.push_back(root->val); preorderTraversal(root->left); preorderTraversal(root->right); return result; } }; */ class Solution //递归解法 { public: vector<int> preorderTraversal(TreeNode* root) { stack<TreeNode*> sta; vector<int> result; if (root != nullptr) { sta.push(root); } while (!sta.empty()) { int size = sta.size(); for (int i = 0; i < size; i++) { TreeNode* node = sta.top(); sta.pop(); result.push_back(node->val); if (node->right) { sta.push(node->right); } if (node->left) { sta.push(node->left); } } } 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; }