zoukankan      html  css  js  c++  java
  • [itint5]判断是否为二叉搜索树

    http://www.itint5.com/oj/#25

    这题在leetcode上是用中序遍历来做的,但是这里由于有相等的情况,即左子树小于等于根,这样中序遍历无法完全判定。可以用递归来做,用递归给出每个子树的上下界。

    #include <climits>
    
    bool isBSTRecur(TreeNode *root, int leftVal, int rightVal) {
        if (root == NULL) return true;
        return (root->val <= rightVal) &&
                (root->val > leftVal) &&
                isBSTRecur(root->left, leftVal, root->val) &&
                isBSTRecur(root->right, root->val, rightVal);
    }
    
    /*
    树结点的定义(请不要在代码中定义该结构)
    struct TreeNode {
      int val;
      TreeNode *left, *right;
    }*/
    bool isBST(TreeNode *root) {
        return isBSTRecur(root, INT_MIN, INT_MAX);
    }
    

      

  • 相关阅读:
    堆排序
    伽马分布
    隔壁-贪心
    对刚—约瑟夫环
    站军姿-两圆并集
    单纯的线性筛素数
    3兔子
    2.圆桌游戏
    1.花
    历史
  • 原文地址:https://www.cnblogs.com/lautsie/p/3527643.html
Copyright © 2011-2022 走看看