重建二叉树并非递归前序/中序/后序遍历

来源:互联网 发布:淘宝买机票怎么取票 编辑:程序博客网 时间:2024/05/21 01:46

《编程之美》3.9重建二叉树的题目:根据中序遍历和前序遍历结果重建二叉树

#include <iostream>#include <cassert>#include <algorithm>#include <stack>using namespace std ; struct NODE {NODE *pLeft;NODE *pRight;char chValue;};void Rebuild(char *preOrder, char *inOrder, int nTreeLen, NODE **pRoot){if(preOrder==NULL&&inOrder==NULL){*pRoot = NULL;return;}if (nTreeLen == 0){return;}if (*pRoot==NULL){*pRoot = new NODE;assert(*pRoot!=NULL);(*pRoot)->pLeft=NULL;(*pRoot)->pRight = NULL;(*pRoot)->chValue = *preOrder;}if (nTreeLen==1){return;}char *preTmp = preOrder;char *inTmp = inOrder;int count=0;while(*inTmp!=*preTmp && count<nTreeLen){if (inTmp==NULL)//这个地方要注意判断一下,不过如果假定输入串没有错误的话,这里一般不会出问题。{return;}inTmp++;count++;}Rebuild(preOrder+1,inOrder,count,&((*pRoot)->pLeft));Rebuild(preOrder+count+1,inOrder+count+1,nTreeLen-count-1,&((*pRoot)->pRight));}void PreOrderTraversalNonrecursive(NODE *proot){stack<NODE*> tStack;if (proot==NULL){return;}tStack.push(proot);while(!tStack.empty()){NODE *pnode = tStack.top();cout << pnode->chValue << " ";tStack.pop();if (pnode->pRight!=NULL){tStack.push(pnode->pRight);}if (pnode->pLeft!=NULL){tStack.push(pnode->pLeft);}}cout << endl;}void InOrderTraversalNonrecursive(NODE *proot){if (proot==NULL){return;}stack<NODE *> tstack;NODE *pnode = proot;while(!tstack.empty() || pnode!=NULL){if (pnode!=NULL){tstack.push(pnode);pnode=pnode->pLeft;}else{pnode = tstack.top();cout << pnode->chValue << " ";tstack.pop();pnode = pnode->pRight;}}cout << endl;}void PostOrderTraversalNonrecursive(NODE *proot){if (proot==NULL){return;}stack<NODE*> s1, s2;NODE* pnode = proot;s1.push(pnode);while(!s1.empty()){pnode = s1.top();s1.pop();if (pnode->pLeft!=NULL){s1.push(pnode->pLeft);}if (pnode->pRight!=NULL){s1.push(pnode->pRight);}s2.push(pnode);}while(!s2.empty()){pnode = s2.top();cout<<pnode->chValue<<" ";s2.pop();}cout<<endl;}int main(){char *preStr= "abdcef";char *inStr = "dbaecf";NODE *pRoot = NULL;Rebuild(preStr,inStr,6,&pRoot);PreOrderTraversalNonrecursive(pRoot);InOrderTraversalNonrecursive(pRoot);PostOrderTraversalNonrecursive(pRoot);system("pause");return 0;}


原创粉丝点击