小渣渣的算法学习笔记:2018秋招备战
数据结构类算法总结:二叉树
数据结构类算法总结:二叉树
1.题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后续遍历结果。例如,输入 {5,7,6,9,11,10,8} 返回true.输入{7,4,6,5}则返回false
2.代码实现:
public class Solution33 { public static void main(String[] args) { Solution33 s = new Solution33(); int a1[] = {5,7,6,9,11,10,8}; int a2[] = {7,4,6,5}; boolean b1 = s.testSequenceOfBst(a1,a1.length); boolean b2 =s.testSequenceOfBst(a2,a2.length); System.out.println(b1); System.out.println(b2); } public boolean testSequenceOfBst(int []sequence,int length){ if(sequence == null || length <= 0) return false; int root = sequence[length - 1]; //在二叉搜索树中左子树结点的值小于根结点的值 int i=0; for(;i<length-1;++i){ if(sequence[i] > root){ break; } } //在二叉搜索树中右子树结点的值大于根结点的值 int j = i; for(;j<length-1;++j){ if(sequence[j]<root) return false; } //判断左子树是不是二叉搜索树 boolean left = true; if(i>0) left = testSequenceOfBst(sequence,i); //判断右子树是不是二叉搜索树 boolean right = true; if(i<length-1) right = testSequenceOfBst(sequence,length-i-1); return (left && right); } }