/** * 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 preorderTraversal(TreeNode *root) { vector res; if (root == NULL) return res; vectorstack; stack.push_back(root); while(!stack.empty()){ TreeNode* n = stack.back(); stack.pop_back(); res.push_back(n->val); if (n->right != NULL) stack.push_back(n->right); if (n->left != NULL) stack.push_back(n->left); } }};
水一发,非递归通用实现见