【序列的异同】
在先序中序、后序中序、层序这三种情况的任意一种下,可唯一确定一颗二叉树
对于非空二叉树来说,当给出前中后序序列中任意两种,根据其相反或相同,有以下判断:
1.前序和中序
- 若相同,则二叉树为右斜树
- 若相反,则二叉树为左斜树
2.前序和后序
- 若相同,则二叉树仅有根结点
- 若相反,则每层仅有一个结点,即二叉树高度为结点个数
3.中序和后序
- 若相同,则二叉树为左斜树
- 若相反,则每层仅有一个结点,即二叉树高度为结点个数
【前序与中序确定二叉树】
前序序列中,第一个结点一定是根结点
在中序序列中,根结点将中序序列分割成左右两个子序列:
- 左子序列:根结点的左子树的中序序列
- 右子序列:根结点的右子树的中序序列
根据这两个序列,在前序序列中找出对应的序列,然后如此递归下去,即可确定唯一的一棵二叉树
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 
 | typedef struct BiTNode {    int data;
 struct BiTNode *lchild;
 struct BiTNode *rchild;
 } BiTNode, *BiTree;
 BiTree createPreInTree(char pre[], char in[], int inStart, int inEnd) {
 static int preIndex = 0;
 
 if (inStart > inEnd)
 return NULL;
 
 BiTNode *root = (BiTNode *)malloc(sizeof(BiTNode));
 root->data = pre[preIndex++];
 root->lchild = NULL;
 root->rchild = NULL;
 
 if (inStart == inEnd)
 return root;
 
 
 int inIndex;
 for (inIndex = inStart; inIndex <= inEnd; inIndex++)
 if (in[inIndex] == root->data)
 break;
 
 
 root->lchild = createPreInTree(pre, in, inStart, inIndex - 1);
 root->rchild = createPreInTree(pre, in, inIndex + 1, inEnd);
 }
 int main() {
 char pre[6] = {'A', 'B', 'D', 'E', 'C'};
 char in[6] = {'D', 'B', 'E', 'A', 'C'};
 int n = 5;
 BiTree root = createPreInTree(pre, in, 0, n - 1);
 
 system("pause");
 return 0;
 }
 
 | 
【后序与中序确定二叉树】
后序序列中,最后一个结点一定是根结点
在中序序列中,根结点将中序序列分割成左右两个子序列:
- 左子序列:根结点的左子树的中序序列
- 右子序列:根结点的右子树的中序序列
根据这两个序列,在后序序列中找出对应的序列,然后如此递归下去,即可确定唯一的一棵二叉树
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 
 | typedef struct BiTNode {    int data;
 struct BiTNode *lchild;
 struct BiTNode *rchild;
 } BiTNode, *BiTree;
 BiTree createPostInTree(char post[], char in[], int inStart, int inEnd, int n) {
 static int postIndex = n - 1;
 
 if (inStart > inEnd)
 return NULL;
 
 BiTNode *root = (BiTNode *)malloc(sizeof(BiTNode));
 root->data = post[postIndex--];
 root->lchild = NULL;
 root->rchild = NULL;
 
 if (inStart == inEnd)
 return root;
 
 
 int inIndex;
 for (inIndex = inStart; inIndex <= inEnd; inIndex++)
 if (in[inIndex] == root->data)
 break;
 
 
 root->rchild = createPostInTree(post, in, inIndex + 1, inEnd, n);
 root->lchild = createPostInTree(post, in, inStart, inIndex - 1, n);
 }
 int main() {
 char in[6] = {'D', 'B', 'E', 'A', 'C'};
 char post[6] = {'D', 'E', 'B', 'C', 'A'};
 int n = 5;
 BiTree root = createPostInTree(post, in, 0, n - 1, n);
 
 system("pause");
 return 0;
 }
 
 | 
【层序与中序确定二叉树】
层序序列中,第一个结点一定是根结点,之后的结点从左到右从上到下按顺序编号
在中序序列中,根结点将中序序列分割成左右两个子序列:
- 左子序列:根结点的左子树的中序序列
- 右子序列:根结点的右子树的中序序列
根据这两个序列,在层序序列中找出对应的序列,然后如此递归下去,即可确定唯一的一棵二叉树