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);
}

  

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-07
  • 2022-12-23
猜你喜欢
  • 2021-08-17
  • 2022-01-26
  • 2022-12-23
  • 2021-08-23
  • 2021-10-13
  • 2021-12-04
  • 2021-11-18
相关资源
相似解决方案