• [二查搜索树]判断一个二查搜索树的后序遍历序列


    对于数组,{5,7,6,9,11,10,8}它是某一个二查搜索树的后序遍历序列,这棵树的样子:

    通过上面的例子可以看出二查搜索树的后序遍历序列的特征是:

    1.序列的最后一个节点是二查搜索树的根节点

    2.序列的前半部分是二查搜索树的左子树,并且都比根节点要小

    3.序列的后半部分是二查搜索树的右子树,并且都比根节点要大

    上面的性质决定了一个序列和一颗二叉树是一一对应的关系。所以代码实现:

    bool VerifySquenceOfBST(int *sequence, int length) 
    {
    	if(sequence == 0 || length <= 0)
    		return false;
    	
    	int root = sequence[length - 1];
    	int i;
    	//check the former part
    	//i:thr number of the former part
    	for(i = 0; i < length -1; i++)
    	{
    		if(sequence[i] > root)
    			break;
    	}
    	//check the last part
    	int j = i;
    	for(; j < length - 1; j++)
    	{
    		if(sequence[j] < root)
    			return false;
    	}
    	
    	//check the left-subtree
    	bool left = true;
    	if(i > 0)
    		left = VerifySquenceOfBST(sequence, i);
    	
    	// check the right-subtree
    	bool right = true;
    	if(i < length -1)
    		right = VerifySquenceOfBST(sequence + i, length - 1 - i);
    	
    	return (left && right);
    }
    

      

  • 相关阅读:
    通俗理解时空效应,感受质量、空间与时间的关系_番外篇
    第四十三象 丙午
    第四十二象 乙巳
    第四十一象 甲辰
    第四十象 癸卯
    ServiceComb简介
    Spring-Session实现Session共享
    SpringBoot整合ActiveMQ
    Hbase配置运行
    KafKa配置运行
  • 原文地址:https://www.cnblogs.com/stemon/p/4881235.html
Copyright © 2020-2023  润新知