zoukankan      html  css  js  c++  java
  • 剑指Offer-- 二叉搜索树的后序遍历序列判断

    版本1:C++

    class Solution {
    public:
        bool VerifySquenceOfBST(vector<int> sequence) {
            if (sequence.size() == 0)
                return false;
            int len = sequence.size(),i = 0,j;
            int root = sequence[len - 1];         // 根节点
            vector<int> leftTree, rightTree;
            while (sequence[i] < root){           // 找出左子树的范围 0 ~ i-1
                leftTree.push_back(sequence[i]);  // 将左子树存入一个vector
                i++;
            }   
            for (j = i; j < len - 1; j++){        // 在右子树的范围 j ~ len-1 内判断有没有不合理的数字
                if (sequence[j] < root){
                    return false;
                }
                rightTree.push_back(sequence[j]);  // 将右子树存入一个vector
            }
            bool resofleft = true, resofright = true;             // 这里的初始化重要,是控制判断为真情况的
            if (leftTree.size() > 0){                             // 保证子树为空时能够跳过判断
                resofleft = VerifySquenceOfBST(leftTree);         // 递归判断左子树
            }
            if (rightTree.size() > 0){
                resofright = VerifySquenceOfBST(rightTree);       // 递归判断右子树
            }
            return (resofleft && resofright);                     // 左右子树都返回为真时,才为真
        }
    };

     版本2:python

    # -*- coding:utf-8 -*-
    class Solution:
        def VerifySquenceOfBST(self, sequence):
            # write code here
            if not sequence:
                return False
            leng = len(sequence)
            root = sequence[leng - 1]
            i = 0
            ltree = []
            rtree = []
            while sequence[i] < root:
                ltree.append(sequence[i])
                i = i + 1
            j = i
            for j in range(j, leng - 1):
                if sequence[j] < root:
                    return False
                rtree.append(sequence[j])
            
            leftTree = True
            rightTree = True
            if len(ltree) :
                leftTree = self.VerifySquenceOfBST( ltree)
            if len(rtree) :
                rightTree = self.VerifySquenceOfBST( rtree)
                
            return (leftTree and rightTree)
  • 相关阅读:
    拼linq 时网上整理的一个类
    ASP.NET MVC controller 之间传JS值
    javascript 事件的一点感悟
    C#扩展特性
    javascript对json对象的序列化与反序列化
    javascript序列化json 第二篇
    单列模式
    Foreach 原理
    浅浅一谈 设计模式
    CRC循环冗余校验码总结(转)
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7007612.html
Copyright © 2011-2022 走看看