https://blog.csdn.net/bendaai/article/details/78675251
一个函数实现树的非递归前、中、后序遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> ans;
void Pre_IN_Post_order(TreeNode *p,int AA) {//AA=1先序 2中序 3后序
TreeNode* sta[10005];//定义一个栈
int top = -1;//栈顶指针
int flag[10005] = {};//记录第几次访问,初始化都是0
sta[++top] = p;
while (top!=-1) {
p = sta[top];
++flag[top];
if (flag[top] == AA) ans.push_back(p->val);
switch (flag[top]) {
case 1:
if (p->left) sta[++top] = p->left; break;
case 2:
if (p->right) sta[++top] = p->right; break;
case 3:
flag[top--]=0;break;//为下一个可能入栈的元素进行初始化
}
}
}
vector<int> preorderTraversal(TreeNode* root) {
if(!root) return ans;
Pre_IN_Post_order(root,1);
return ans;
}
};