根据树的两种遍历序列求第三种遍历序列
生活随笔
收集整理的這篇文章主要介紹了
根据树的两种遍历序列求第三种遍历序列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
只知道先序序列和后序序列是無法求出唯一的樹,所以不做討論。
#include<iostream> #include<cstdio> #include<cstring> using namespace std;struct BinaryTreeNode {char c;BinaryTreeNode *lchild, *rchild;BinaryTreeNode(){lchild = NULL, rchild = NULL;} }; struct BinaryTreeNode *root1,*root2;char preorder[100], inorder[100], postorder[100];void preSearch(BinaryTreeNode *root) //先序遍歷樹 {if(root != NULL){printf("%c", root->c);preSearch(root->lchild);preSearch(root->rchild);}return ; }void midSearch(BinaryTreeNode *root) //中序遍歷樹 {if(root != NULL){midSearch(root->lchild);printf("%c", root->c);midSearch(root->rchild);}return ; }void postSearch(BinaryTreeNode *root) //后序遍歷樹 {if(root != NULL){postSearch(root->lchild);postSearch(root->rchild);printf("%c", root->c);}return ; }void BuildTreeFromPreAndMid(BinaryTreeNode * &root, int ll, int lr, int len, int &now)//根據中序和先序求樹 {root = new BinaryTreeNode();root->c = *(preorder + now);int pos = (int)(strchr(inorder, *(preorder + now)) - inorder); //查找字符串中首次出現某個字符的位置 now++;if(now >= len)return ;if(pos - 1 >= ll){BinaryTreeNode *t = new BinaryTreeNode();root->lchild = t;BuildTreeFromPreAndMid(root->lchild, ll, pos - 1, len, now);}if(pos + 1 <= lr){BinaryTreeNode *t = new BinaryTreeNode();root->rchild = t;BuildTreeFromPreAndMid(root->rchild, pos + 1, lr, len, now);} }void BuildTreeFromPostAndMid(BinaryTreeNode * &root, int ll, int lr, int len, int &now)//根據中序和后序求樹 {root = new BinaryTreeNode();root->c = *(postorder + now);int pos = (int)(strchr(inorder, *(postorder + now)) - inorder);now--;if(now < 0)return ;if(pos + 1 <= lr){BinaryTreeNode *t = new BinaryTreeNode();root->rchild = t;BuildTreeFromPostAndMid(root->rchild, pos + 1, lr, len, now);}if(pos - 1 >= ll){BinaryTreeNode *t = new BinaryTreeNode();root->lchild = t;BuildTreeFromPostAndMid(root->lchild, ll, pos - 1, len, now);} }//釋放二叉樹 inline void DeleteBinaryTree(BinaryTreeNode * &root) {if(root){DeleteBinaryTree(root->lchild); //釋放左子樹DeleteBinaryTree(root->rchild); //釋放右子樹delete root; //釋放根結點} }int main(void) {gets(preorder);gets(inorder);//gets(postorder);int now = 0;BuildTreeFromPreAndMid(root1, 0, strlen(preorder) - 1, strlen(preorder), now);//int now2 = strlen(postorder)-1;//BuildTreeFromPostAndMid(root2, 0, strlen(postorder) - 1, strlen(postorder), now2);postSearch(root1);puts("");DeleteBinaryTree(root1);/*preSearch(root2);puts("");DeleteBinaryTree(root2);*/return 0; }
總結
以上是生活随笔為你收集整理的根据树的两种遍历序列求第三种遍历序列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最短路径Dijkstra(静态邻接表+优
- 下一篇: 用位运算实现四则运算之加减乘除(用位运算