zoukankan      html  css  js  c++  java
  • careercup-树与图 4.5

    4.5 实现一个函数,检查一棵二叉树是否为二叉查找树。

    参考:http://blog.csdn.net/sgbfblog/article/details/7771096

    C++实现代码:

    #include<iostream>
    #include<new>
    #include<climits>
    using namespace std;
    
    struct TreeNode
    {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    void insert(TreeNode *&root,int key)
    {
            if(root==NULL)
                root=new TreeNode(key);
            else if(key<root->val)
                insert(root->left,key);
            else
                insert(root->right,key);
    }
    void creatBST(TreeNode *&root)
    {
        int arr[10]= {29,4,6,1,8,3,0,78,23,89};
        for(auto a:arr)
            insert(root,a);
    }
    bool ishelper(TreeNode *root,int min,int max)
    {
        if(root==NULL)
            return true;
        if(root->val<=min||root->val>=max)
            return false;
        return ishelper(root->left,min,root->val)&&ishelper(root->right,root->val,max);
    }
    bool isBST(TreeNode *root)
    {
        return ishelper(root,INT_MIN,INT_MAX);
    }
    void inorder(TreeNode *root)
    {
        if(root)
        {
            inorder(root->left);
            cout<<root->val<<" ";
            inorder(root->right);
        }
    }
    
    int main()
    {
        TreeNode *root=NULL;
        creatBST(root);
        inorder(root);
        cout<<endl;
        cout<<isBST(root)<<endl;
    }
  • 相关阅读:
    python之路3-元组、列表、字典、集合
    python之路2-字符串操作
    Python之路1-变量、数据类型、循环语法
    config模块
    os模块
    logging模块
    控制台报错定位问题所在
    time模块
    random模块
    列表生成
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4148068.html
Copyright © 2011-2022 走看看