寫迭代實現的實在沒什麼意思,這裏寫個用棧實現的吧:code
#include <vector> #include <stack> #include <algorithm> /** * Definition for binary tree * 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) { std::vector<int> result; std::stack<TreeNode *> _stack; if (root == NULL) return result; _stack.push(root); while (!_stack.empty()) { TreeNode *cur = _stack.top(); _stack.pop(); result.push_back(cur->val); TreeNode *right = cur->right; if (right) _stack.push(right); TreeNode *left = cur->left; if (left) _stack.push(left); } return result; } };