一个先序或后序序列 还原唯一 二叉排序树 (C语言实现)

来源:互联网 发布:有声朗读软件ios 编辑:程序博客网 时间:2024/05/18 18:54

以下为本人个人观点,如有问题,欢迎指正。

首先是说明,一个先序序列,或者后序序列是否可以确定一个唯一的二叉排序树(BST)


众所周知,1、一个先序或后序序列,与中序序列可以还原一个二叉树。

     2、二叉排序树的中序序列为顺序序列,即如果知道先序或后序序列,我们就能推出它的中序序列。

所以,一个先序序列,或者后序序列可以确定一个唯一的二叉排序树(BST)。


还原思路1.根据众所周知2,我们通过先序或或许得到中序,如

先序: 7 5 4 6 9 8 10

中序: 4 5 6 7 8 9 10

已知中序和先序,就与普通还原二叉树方法一样了。


还原思路2.,因为二叉排序树的主要特征是,一个非叶子节点的左子树上所有节点值都比该节点小,而其右子树中的所有节点值都比该节点大。所以对于一个先序序列,

7 5 4 6 9 8 10 我们遍历这个序列,直到找到第一个比a[0]大的节点下标index(这里为比7大的,即值是9,下标为4),

即可确定左子树(1到index-1)与右子树(index到length-1)。

则通过递归,就可还原这个二叉排序树。


思路2代码://写的不好,比较乱,仅供参考,最好自己去实现

#include <stdio.h>#include <stdlib.h>struct BinaryTreeNode {    int value;    BinaryTreeNode *pLeft;    BinaryTreeNode *pRight;     };void InOrder(BinaryTreeNode * root) {    if(root == NULL)         return;    InOrder(root->pLeft);    printf("%d ", root->value);    InOrder(root->pRight);}void RestructBST(BinaryTreeNode * root, const int *preOrderArr, int length) {                                           if(length < 1 || root == NULL || preOrderArr == NULL)        return;    int leftLength, rightLength;         BinaryTreeNode *leftChild = (BinaryTreeNode *) malloc(sizeof (BinaryTreeNode) );    leftChild->value = preOrderArr[0];    leftChild->pLeft = NULL;    leftChild->pRight = NULL;        root->pLeft = leftChild;        int RightChildindex = 0;    for(; RightChildindex<length; ++RightChildindex) {        if(preOrderArr[RightChildindex] > root->value)            break;        ++leftLength;    }        BinaryTreeNode *rightChild = NULL;    if(RightChildindex != 0 && RightChildindex < length) {        rightChild = (BinaryTreeNode *) malloc(sizeof (BinaryTreeNode));        rightChild->value = preOrderArr[RightChildindex];        rightChild->pLeft = NULL;        rightChild->pRight = NULL;                root->pRight = rightChild;         length--;           }    --leftLength;     rightLength = length - leftLength - 1;        RestructBST(leftChild, preOrderArr + 1, leftLength);    RestructBST(rightChild, preOrderArr + RightChildindex + 1, rightLength);}int main() {       int num = 0;    int arr[100];    while(scanf("%d", &num) != EOF) {       for(int i=0; i<num; ++i)             scanf("%d", &arr[i]);        BinaryTreeNode * root = (BinaryTreeNode *) malloc(sizeof (BinaryTreeNode));        root->value = arr[0];        root->pLeft = NULL;        root->pRight = NULL;        RestructBST(root, arr + 1, num - 1);        InOrder(root);        free(root);        printf("\n");             }    return 0;} 


0 0