面试题24:二叉搜索树的后序遍历序列

问题说明:

1.二叉搜索树又名二叉排序树,即左孩子小于根结点,右孩子大于根结点;

2.给定一个整数数组序列,判定该序列是否为某个二叉搜索树的后序序列;

3.假设输入的数组任意两个数字各不相同。

// judge post sequence is some binarySearchTree post travel squence
public static boolean isPostSequenceOfBST(int[] post){
	int len = 0;
	if(null == post ||(len = post.length) == 0){
		throw new IllegalArgumentException();
	}
	return isPostSequenceOfBST(post, 0, len - 1);
}
private static boolean isPostSequenceOfBST(int[] post, int postBegin, int postEnd){
	// postBegin > postEnd
	if(postBegin > postEnd){
		return false;
	}
	// postBegin == postEnd
	boolean isSingleTree = (postBegin == postEnd);
	if(isSingleTree){
		return true;
	}
	// postBegin < postEnd
	int rootValue = post[postEnd];
	// equal to rightBeginIndex first index of more than rootValue
	// at most equal to postEnd
	
	int firstMoreThanIndex = postBegin;
	while(firstMoreThanIndex < postEnd && post[firstMoreThanIndex] < rootValue){
		firstMoreThanIndex ++;
	}
	int rightExclusiveEndIndex = firstMoreThanIndex + 1;
	while(rightExclusiveEndIndex < postEnd){
		if(post[rightExclusiveEndIndex] < rootValue){
			  return false;
		}
		rightExclusiveEndIndex ++;
	}
	// rightExclusiveEnd == postEnd
	int leftTreeLen = firstMoreThanIndex - postBegin;
	int rightTreeLen = rightExclusiveEndIndex - firstMoreThanIndex;
	boolean isLeftTreeOrNull =(leftTreeLen != 0 ? isPostSequenceOfBST(post, postBegin, firstMoreThanIndex - 1) : true);
	boolean isRightTreeOrNull =(rightTreeLen != 0 ? isPostSequenceOfBST(post, firstMoreThanIndex, rightExclusiveEndIndex - 1) : true);		
	return (isLeftTreeOrNull && isRightTreeOrNull);
	
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值