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

题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

思路:
本题的考点是递归,由于数组表示的是二叉树的后续遍历,最后一个数字就是根节点的值。二叉搜索树的特点是,左子树节点的值 < 根节点的值 < 右子树节点的值。根据这个特点可以将数组划分成两部分,一部分是左子树,它们的值都大小于根节点,另一部分是右子树,它们的值都大于根节点。然后使用同样的方法分析左子树和右子树,是一个递归的过程。

这里写图片描述

Java 代码:

public class Solution {
    public boolean VerifySquenceOfBST(int[] s) {
        if(s.length == 0) return false;
        return check(s, 0, s.length-1);
    }
    public boolean check(int[] a, int l, int r) {
    	if(l >= r) return true;
    	int x = a[r];
    	int r1 = l;
    	while(a[r1] < x) r1++;
    	int l1 = r1;
    	int i = l1;
    	while(i < r) {
    		if(a[i] < x) return false; 
    		i++;
    	}
    	return check(a, l, r1 - 1) && check(a, l1, r - 1);
    }
}


写法2public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        if (sequence.length == 0) return false;
        return verify(sequence, 0, sequence.length - 1);
    }
    
    private boolean verify(int[] sequence, int start, int end) {
        if (start >= end) return true;
        int leftEnd = start;
        while (sequence[leftEnd] < sequence[end]) leftEnd++;
        for (int rightStart = leftEnd; rightStart < end; rightStart++) {
            if (sequence[rightStart] < sequence[end]) {
                return false;
            }
        }
        return verify(sequence, start, leftEnd - 1) &&
               verify(sequence, leftEnd, end - 1);
    }
}

Python 代码:

# -*- coding:utf-8 -*-
class Solution:
    def VerifySquenceOfBST(self, sequence):
        if not sequence:
            return False
        return self.check(sequence, 0, len(sequence) - 1)
    
    def check(self, sequence, left, right):
        if left >= right:
            return True
        r = left
        while sequence[r] < sequence[right]:
            r += 1
        i = l = r      
        while i < right:
            if sequence[i] < sequence[right]:
                return False
            i += 1
        return self.check(sequence, left, r - 1) and self.check(sequence, l, right - 1)

相关题目:

1、输入一个整数数组,判断该数组是不是BST的前序遍历结果。

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值