总结下二叉树的已知两种遍历方式求第三种遍历顺序的方法,已知先序和中序遍历或者后序与中序遍历后二叉树是唯一确定的,下面介绍怎么求出第三种遍历顺序。
先序遍历顺序为:根结点——左子结点——右子结点,中序遍历为:左子结点——根结点——右子结点,我们注意到,先序遍历的第一个元素就是二叉树根结点,我们在中序遍历中以该元素分为左右两部分,则左边为左子树,右边为右子树,递归即可还原二叉树,这个过程中可直接输出后序遍历的顺序。同理,可以用后序与中序还原出先序遍历的顺序。
代码及测试数据如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <malloc.h> 6 #include <string> 7 #include <vector> 8 #include <stack> 9 #include <queue> 10 #include <set> 11 #include <map> 12 13 #define FRER() freopen("in.txt", "r", stdin); 14 15 using namespace std; 16 17 //函数状态码定义 18 #define TRUE 1 19 #define FALSE 0 20 #define OK 1 21 #define ERROR 0 22 #define INFEASIBLE -1 23 #define OVERFLOW -2 24 25 typedef char TElemType; 26 typedef int Status; 27 28 typedef struct BiNode { 29 TElemType data; 30 struct BiNode *lchild, *rchild; 31 }BiNode, *BiTree; 32 33 BiTree BinaryTreeFormorderings(char *, char *, int); 34 BiTree BinaryTreePostorderings(char *, char *, int); 35 36 /* 37 ABDECFG 38 DBEAFCG 39 DEBFGCA 40 */ 41 42 int main() 43 { 44 FRER() 45 int n; 46 char str[100], ptr[100]; 47 cin >> n >> str >> ptr; 48 BinaryTreePostorderings(str, ptr, n); 49 return 0; 50 } 51 52 BiTree BinaryTreeFormorderings(char *pre, char *in, int len) { 53 if(len <= 0) 54 return NULL; 55 BiNode *node = new BiNode; 56 node->data = *pre; 57 int idx = 0; 58 while(idx < len) { 59 if(*(in + idx) == *pre) 60 break; 61 ++idx; 62 } 63 node->lchild = BinaryTreeFormorderings(pre + 1, in, idx); 64 node->rchild = BinaryTreeFormorderings(pre + idx + 1, in + idx + 1, len - (idx + 1)); 65 cout << node->data << ‘ ‘; 66 return node; 67 } 68 69 BiTree BinaryTreePostorderings(char *in, char *post, int len) { 70 if(len == 0) 71 return NULL; 72 BiNode *node = new BiNode; 73 node->data = *(post + len - 1); 74 cout << node->data << ‘ ‘; 75 int idx = 0; 76 while(idx < len) { 77 if(*(in + idx) == *(post + len - 1)) 78 break; 79 ++idx; 80 } 81 node->lchild = BinaryTreePostorderings(in, post, idx); 82 node->rchild = BinaryTreePostorderings(in + idx + 1, post + idx, len - (idx + 1)); 83 return node; 84 }
原文地址:https://www.cnblogs.com/fan-jiaming/p/9822765.html
时间: 2024-10-10 21:58:13