9、判断整数序列是不是二元查找树的后序遍历结果

来源:互联网 发布:修仙记神翼进阶数据 编辑:程序博客网 时间:2024/05/09 23:44
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
  8
  / \
  6 10
  / \ / \
  5 7 9 11
因此返回true。

如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。


分析:二元查找树的后续遍历元素中,最后一个元素是根节点,然后左边元素中比根节点大的元素是右子树,比根节点小的是左子树。

可以根据这个特性递归判断。


下面给出程序代码:


#include <stdio.h>int a[20],len;int JudgeLeft(int start,int end,int root);int Fun(int start,int root);int main(){int i;while (printf("Input Number of Digit:  "),scanf("%d",&len)!=EOF){printf("Please input %d numbers: \n",len);for (i=0;i<len;i++){scanf("%d",&a[i]);}if (Fun(0,len-1)){printf("True\n");}else{printf("False\n");}printf("\n");}return 0;}int Fun(int start,int root){int mid;if (start==root||start>root){return 1;}for(mid=root-1;mid>=0&&a[mid]>=a[root];mid--);mid++;if (JudgeLeft(start,mid-1,root)==0){return 0;}return Fun(start,mid-1)&&Fun(mid,root-1);}int JudgeLeft(int start,int end,int root){int i;for (i=start;i<=end;i++){if (a[i]>=a[root]){return 0;}}return 1;}