剑指Offer-24
来源:互联网 发布:阿里云怎么监控 编辑:程序博客网 时间:2024/06/06 03:19
题目:
二叉搜索树的后续遍历
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。
如果是则返回true。否则返回false。假设输入的数组的任意两个数字都互不相同。
实现
// coding = javapublic class Solution24 { public static boolean verifySequenceOfBST(int[] data){ if(data == null || data.length<1){ return false; } return verifySequenceOfBST(data,0,data.length-1); } public static boolean verifySequenceOfBST(int[] data,int start,int end){ if(start>=end){ return true; } int index = start; while(index<end-1 && data[index]<data[end]){ index++; } int right = index; while (index<end-1 && data[index]>data[end]){ index++; } if(index!=end-1){ return false; } index = right; return verifySequenceOfBST(data,start,index-1) && verifySequenceOfBST(data,index,end-1); } public static void main(String[] args) { // 10 // / \ // 6 14 // /\ / \ // 4 8 12 16 int[] data = {4, 8, 6, 12, 16, 14, 10}; System.out.println("true: " + verifySequenceOfBST(data)); // 5 // / \ // 4 7 // / // 6 int[] data2 = {4, 6, 7, 5}; System.out.println("true: " + verifySequenceOfBST(data2)); // 5 // / // 4 // / // 3 // / // 2 // / // 1 int[] data3 = {1, 2, 3, 4, 5}; System.out.println("true: " + verifySequenceOfBST(data3)); // 1 // \ // 2 // \ // 3 // \ // 4 // \ // 5 int[] data4 = {5, 4, 3, 2, 1}; System.out.println("true: " + verifySequenceOfBST(data4)); // 树中只有1个结点 int[] data5 = {5}; System.out.println("true: " + verifySequenceOfBST(data5)); int[] data6 = {7, 4, 6, 5}; System.out.println("false: " + verifySequenceOfBST(data6)); int[] data7 = {4, 6, 12, 8, 16, 14, 10}; System.out.println("false: " + verifySequenceOfBST(data7)); }}
阅读全文
1 0
- 剑指Offer-24
- 剑指offer题24
- 剑指offer面试题24
- 剑指OFFER
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 剑指Offer
- 剑指offer
- 剑指offer
- 《剑指offer》
- xiaocms文件上传GETSHELL
- 三指截屏
- 商品展示案例
- 欢迎使用CSDN-markdown编辑器
- mysql 修改root密码和开启远程访问
- 剑指Offer-24
- 支持向量机讲解
- The event in requested index is outdated and cleared (the requested history has been cleared ) 问题和修复
- python cookbook学习笔记十四:函数(1)
- Python数据分析与挖掘实战(开发流程及常用库安装)
- linux sed 批量替换字符串
- CentOS 7下安装Python3.5
- 什么是工程师文化?
- UNIX ftp命令