二叉树的pre-order,post-order,in-order遍历用recursion实现非常简单,本文中的代码为基于stack的非recursion的实现方法。另外还有level-order的实现。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
Pre-order
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
if(root==NULL) return vector<int> ();
vector<int> result;
stack<TreeNode *> tmp;
tmp.push(root);
while(!tmp.empty()){
TreeNode *cur = tmp.top();
result.push_back(cur->val);
tmp.pop();
if(cur->right!=NULL) tmp.push(cur->right);
if(cur->left!=NULL) tmp.push(cur->left);
}
return result;
}
};
Post-order
class Solution {
public:
&nb