# c++实现二叉树的非递归创建以及非递归先序、中序、后序遍历

```TreeNode* createTree(int *arr, int length) {
if(length<1) return NULL;
TreeNode* root = new TreeNode(arr[0]);
deque<pair<TreeNode*,int> > route;
route.push_back(make_pair(root,0));
while(!route.empty()) {
TreeNode* temp = route.front().first;
int ct = route.front().second;
route.pop_front();
if(2*ct+1<length) {
temp->left = new TreeNode(arr[2*ct+1]);//创建当前节点的左叶子
route.push_back(make_pair(temp->left,2*ct+1));
}
if(2*ct+2<length) {
temp->right = new TreeNode(arr[2*ct+2]);//创建当前节点的右叶子
route.push_back(make_pair(temp->right,2*ct+2));
}

}
return root;
}```

```void PostOrder(TreeNode* root) {
deque<pair<TreeNode*, bool> > route;
route.push_back(make_pair(root, false));
while(!route.empty()) {
TreeNode* root = route.back().first;
bool visit = route.back().second;
route.pop_back();
if(root==NULL)
continue;
if(visit) {
cout << root->val << ' ';
} else {//改变下面三者的顺序就可以实现三种排序
route.push_back(make_pair(root, true));
route.push_back(make_pair(root->right, false));
route.push_back(make_pair(root->left, false));

}
}
}```

原文作者：輪迴之間
原文地址: https://www.cnblogs.com/nice-forever/p/6762804.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。