题:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路:根据二叉搜索树的特性以及二叉树的后序遍历特性我们可以知道,数组的最后一个数字为二叉搜索树的根节点,从数组的第一位开始,直到第一个数值大于根节点的位置,为二叉搜索树的左子树,剩下的为二叉搜索树的右子树。因为二叉搜索树的特点是左小右大,所以如果右子树里面出现小于根节点的数值,说明这个数组不是二叉搜索树的后序遍历序列。 综合以上,我们可以用递归一直遍历到树的叶子结点,如果没有出现以上情况则说明这个数组是二叉搜索树的后序遍历序列。
代码:
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence.length == 0 || sequence == null)
return false;
int root = sequence[sequence.length-1];
int[] leftTree = new int[sequence.length];
int[] rightTree = new int[sequence.length];// 左右子树先初始化为原数组大小
int lCount=0, rCount;// 左右子树结点个数
while (sequence[lCount] < root){
leftTree[lCount] = sequence[lCount];
lCount++;
}// 先取出左子树
rCount = sequence.length-lCount-1;// 右子树的节点个数=总长度-左子树的节点个数-根节点
System.arraycopy(sequence, lCount, rightTree, 0, rCount);// 取出右子树
for(int i = 0; i < rCount; i++){
if(rightTree[i] < root)
return false;
}// 如果右子树里有小于根节点的数值,直接返回false
// 这里初始化为true的原因为:
// 两个if的条件都是在左(右)子树的节点大于1,如果左(右)子树中有节点数小于1的,则不需要验证。
boolean bLeft = true;
boolean bRight = true;
if(lCount > 1) {
int[] newLeftTree = new int[lCount];
System.arraycopy(leftTree, 0, newLeftTree, 0, lCount);
bLeft = VerifySquenceOfBST(newLeftTree);// 递归验证左子树
}
if(rCount > 1){
int[] newRightTree = new int[rCount];
System.arraycopy(rightTree, 0, newRightTree, 0, rCount);
bRight = VerifySquenceOfBST(newRightTree);// 递归验证右子树
}
return bLeft && bRight;
}
}
呕心沥血写出来的,转载请一定注明出处!