剑指offer66题--Java实现,c++实现和python实现 23.二叉搜索树的后序遍历序列

题目描述

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

C++

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        return sequence.size()==0? false:SquenceOfBST(sequence,0,sequence.size());
    }

   bool SquenceOfBST(vector<int> &sequence, int l, int r)
    {
        if (l == r)
            return true;
        int mid = l, last = 0;
        for (; mid < r - 1 && sequence[mid] < sequence[r - 1]; ++mid);
        for (last = mid; last < r - 1 && sequence[last] > sequence[r - 1]; ++last);
        return last == r - 1 && SquenceOfBST(sequence, l, mid) && SquenceOfBST(sequence, mid, r - 1);
    }
};

Java

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
         if (null == sequence || sequence.length == 0) {
            System.out.println("数组为null");
            return false;
        }
        int n = sequence.length;
        return verify(sequence, 0, n-1);
    }
    
    private boolean verify(int [] sequence, int start, int stop) {//最开始的start表示索引0,stop表示索引为n-1
        if (start >= stop) {
            return true;
        }
        int root = sequence[stop];//拿到根节点
        int i = start;
        for (;i<stop;i++) {//一直到当前的根节点
            if (root < sequence[i]) {//当找到大于root节点的元素时跳出来
                break;
            }
        }
        int j = i;//之所以换一个变量,是为了保存 i此时所在的位置,方便之后针对左右子树分别处理
        for (;j<stop;j++) {
            if (root > sequence[j]) {//如果二叉搜索树的右子树中有比root节点小的节点,则证明不对
                return false;
            }
        }
        return verify(sequence, start, i-1) && verify(sequence, i, stop-1);
    }
}

python

class Solution:
    def VerifySquenceOfBST(self, sequence):
        if sequence == []:
            return False
        if len(sequence) == 1 or len(sequence) == 2:
            return True
        else:
            root = sequence.pop(-1)
            sign = 0
            note = 0
            flag = 0
            for i in range(len(sequence)):
                if sign is 0 and sequence[i] > root:
                    note = i
                    sign = -1
                if sequence[i] > root:
                    sign = 1
                    flag += 1
                if (sign == 1) and (sequence[i] < root):
                    return False
            if sign is 0:
                note = i
            if flag == len(sequence):
                note = 1
            return self.VerifySquenceOfBST(sequence[:note]) and self.VerifySquenceOfBST(sequence[note:])

 

发布了49 篇原创文章 · 获赞 2 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术工厂 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览