• 剑指offer33:二叉搜索树的后序遍历序列


    题目描述

    输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。
     
    该题目两个隐藏的知识点:
    1. 二叉搜索树(即二叉排序树)中序遍历序列即为该序列的一个有序序列,相当于题目中给出了一个中序遍历序列和一个后序遍历序列,那么我们可以唯一确定一颗二叉树
    2. 树的遍历过程即一个出栈入栈的过程,因此,令一个序列为入栈序列,一个序列为出栈序列,利用《栈的压入、弹出序列》该题目的思想即可求解。
    class Solution {
    public:
        bool VerifySquenceOfBST(vector<int> sequence) {
            if(sequence.size()==0) return false;
            vector<int> inOrder(sequence);
            sort(inOrder.begin(),inOrder.end());
            stack<int> s;
            int j = 0;
            for(int i=0;i<inOrder.size();i++){
                s.push(inOrder[i]);
                while(!s.empty()&&s.top()==sequence[j]){
                    s.pop();
                    j++;
                }
            }
         s.empty();
     } };

    使用递归的方式求解:

    public class Solution {
        public boolean VerifySquenceOfBST(int [] sequence) {
            if(sequence.length==0) return false;
           
            return verifyPostorder(sequence,0,sequence.length-1);
        }
        public boolean verifyPostorder(int [] sequence,int start,int end){
            if(end - start <= 0) return true;
            int num = sequence[end];
            int index = start;
            while(sequence[index]<num&&index<=end-1) index++;
            int split = index;
            
            while(sequence[index]>num&&index<=end-1) index++;
            if(index != end)
                return false;
            return verifyPostorder(sequence,start,split-1)&&verifyPostorder(sequence,split,end-1);
        }
    }
  • 相关阅读:
    Unity3d限制帧数
    Linux 后台运行程序
    Flask异步发送邮件的方法
    [转]视图多表
    dede 织梦手机静态化一键生成插件
    如何在wordpress中设置关键词和描述
    前端PS切图
    帝国cms用自定义列表页做首页
    帝国cms 滚动加载更多整合
    swiper 自定义pagination 样式内容
  • 原文地址:https://www.cnblogs.com/ttzz/p/13828765.html
Copyright © 2020-2023  润新知