题目
思路 --(非常典型的递归)
由于是后续遍历 ,所以数组的最后一位 一定是根节点 ,根据二叉搜索树的性质,我们可以知道 左节点的值小于根节点小于右节点,可以定义一个标志位 left ,表示当前右子树开始的下标
只要index【left】< root 说明 还是在左子树中 ,当找到 右子树的起点 之后,可以对整个右子树遍历 ,如果都大于root的值 ,可以根据 left 的值 将整个数组 分为左右子树的数组,递归 进行
最后返回的条件是 :: 遍历到了 根节点中的根节点
代码实现
/**
*
*/
/***
* @author 18071
* @Date 2019年3月11日
* 功能:二叉搜索树的后序遍历 ---
***/
public class test {
public static void main(String args[]) {
int [] index = {5,7,6,9,11,10,8};
Solution s =new Solution ();
s.find(index);
}
}
class Solution {
public void find(int [] index ) {
//为空检测
if(index == null) {
return ;
}
int left=0;
int right=index.length-1;
System.out.println(core(index,left,right));
}
public boolean core(int [] x ,int left ,int right) {
//结束递归条件
if(left >= right) {
return true;
}
int root =x[right];//根节点值
while(x[left]<root) {
left++;
}
//left +1 ;//右子树 的 开始节点
for(int i=left+1 ;i<right;i++) {
if(x[i]<root ) {
return false;
}
}
return core(x,0,left-1)&&core(x,left+1,right-1);
}
}