zoukankan      html  css  js  c++  java
  • 判断整数序列是不是二元查找树的后序遍历结果

    题目:输入一个整数数组,判断该数组是不是二元查找树的后序遍历结果,如果是,返回true,否则返回假,具体实现如下:

    #include <iostream>
    using namespace std;
    //搜索树后序遍历数组最后一个是根,从数组头到第一个比根大的节点是左孩子,后面右孩子必须全大于根,递推
    static bool VerifyArrayOfBST(int a[], int start, int length)
    {
    	if (a[length]<a[start])
    	{
    		return false;
    	}
    	if (length == 0)
    	{
    
    		for (int i = 0; i <= length; i++)
    		{
    			if (a[i + start]>a[length + start])
    			{
    				if (i>0)
    				{
    					VerifyArrayOfBST(a, start, i);
    
    				}
    				if (length - i>0)
    				{
    					VerifyArrayOfBST(a, start + i, length - i);
    				}
    
    			}
    		}
    	}
    	return true;
    }
    int main(int argc, char * argv[])
    {
    	int a[] = { 1, 6, 4, 3, 5 };
    	int a1[] = { 7, 6, 4, 3, 5 };
    	VerifyArrayOfBST(a, 0, 4);
    	VerifyArrayOfBST(a1, 0, 4);
    	if (VerifyArrayOfBST(a, 0, 4) == true)
    	{
    		cout << "a是搜索树" << endl;
    	}
    	else{
    		cout << "a不是搜索树" << endl;
    	}
    	if (VerifyArrayOfBST(a1, 0, 4) == true)
    	{
    		cout << "a1是搜索树" << endl;
    	}
    	else{
    		cout << "a1不是搜索树" << endl;
    	}
    	system("pause");
    	return 0;
    }
    运行效果如图1所示:

    图1 运行效果


  • 相关阅读:
    iOS CoreData使用笔记
    iOS UIWebView中添加手势
    Swift sha1 md5加密
    Swift用block响应UIAlertView和UIActionSheet的按钮点击事件
    iOS判断iPhone型号
    iOS Document Interaction 编程指南
    Swift项目开发中缓存计算以及清除
    SVN 一次性提交多个目录中文件
    svn 相关
    sublime text 2相关
  • 原文地址:https://www.cnblogs.com/new0801/p/6176917.html
Copyright © 2011-2022 走看看