zoukankan      html  css  js  c++  java
  • 判断整数序列是不是二元查找树的后序遍历结果

    题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历结果。如果是,返回true,否则返回false。

    举例:输入5、7、6、9、11、10、8,由于这个整数序列有如下的树的后序遍历结果:

                                       8   
                                     /   \
    576911108   ->        6     10
                                   / \    / \
                                  5   7  9   11

    因此返回true。

    如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,所以返回false。

    答:二叉树的后序遍历

    #include "stdafx.h"
    #include <iostream>
    
    using namespace std;
    
    /*                                 8 
                                     /   \
    5、7、6、9、11、10、8 ->          6     10
                                   / \    / \
                                  5   7  9   11
    */
    
    bool IsPostTreeTraversal(int arr[], int length)
    {
        if (length <= 0 || NULL == arr)
        {
            return false;
        }
        int root = arr[length - 1];
        int m = 0;
        for (; m < length - 1; m++)
        {
            if (arr[m] > root)
            {
                break;
            }
        }
        int n = m;
        for (; n < length - 1; n++) //如果右子树小于根节点就返回false
        {
            if (arr[n] < root)
            {
                return false;
            }
        }
        int left = true;
        if (m > 0)
        {
            left = IsPostTreeTraversal(arr, m);
        }
        
        int right = true;
        if (length - m - 1 > 0)
        {
            right = IsPostTreeTraversal(arr, length - m - 1);
        }
    
        return (left && right);
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        int arr[] = {5, 7, 6, 9, 11, 10, 8};
        if (IsPostTreeTraversal(arr, 7))
        {
            cout<<"true"<<endl;
        }
        else
        {
            cout<<"false"<<endl;
        }
        return 0;
    }

    输出界面如下:

  • 相关阅读:
    Rolling Hash(Rabin-Karp算法)匹配字符串
    vim下单行长文本的时候卡顿解决办法
    设置vim的默认工作路径同时与自动设当前编辑的文件所在目录为当前工作路径不冲突
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
    Careercup
  • 原文地址:https://www.cnblogs.com/venow/p/2649673.html
Copyright © 2011-2022 走看看