【二叉搜索树BST】98. Validate Binary Search Tree

问题:

判断一颗二叉树是否为二叉搜索树。

解法:Binary Tree(二叉树)

首先,了解 二叉搜索树BST的定义:

A binary search tree is a rooted binary tree whose internal nodes each store a key greater than all the keys in the node's left subtree and less than those in its right subtree.

-> left < root < right

e.g. 下图中,2 < 5 < 6

求给定函数  bool isValidBST(TreeNode* root)

而本题目中,例如节点4,不能只判断4只要>2就好,同时4还得<5,这就不止一个变量(当前节点root)能完全覆盖。

每次递归中由3个随递归调用变化的变量:

当前节点root,当前节点的最小值min(开区间,不取到),当前节点的最大值max(开区间,不取到)。

因此,我们追加辅助递归函数,bool isValidBSThelp(TreeNode* root, TreeNode* min, TreeNode* max)

  • DEF
    • 判断:当前节点root是否有 [ min < root < max ],即 (min, max)
      • 若没有,即 [ min >= root or root >= max ],则返回false。
      • 否则,本层root没问题,继续递归判断 root->left 和 root->right。这时判断范围:
        • root->left: (min, root)
        • root->right: (root, max)
  • STAT
    • 当前节点 root
    • 开区间最小值 min
    • 开区间最大值 max
  • OPT
    • 得到递归结果left和right后,返回
      • left && right
  • BASE
    • root==null,return true
    • min!=null,if [min >= root] return false
    • max!=null, if [root >= max] return false

代码参考:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     //DEF:
15     //   to find if: [min < root < max]
16     // if [min>=root or root>=max] then return false
17     // else this level is good, then check the next level recursionly:
18     //      to find if [min < root->left < root] && [root < root->right < max]
19     //STAT: root, min, max
20     //OPT: after got the result as left, right.
21     //     return left && right
22     //BASE:
23     //    root==null, return true
24     //    min!=null->if [min>=root], return false
25     //    max!=null->if [root>=max], return false
26     bool isValidBSThelp(TreeNode* root, TreeNode* min, TreeNode* max) {
27         if(!root) return true;
28         if(min && min->val >= root->val) return false;
29         if(max && max->val <= root->val) return false;
30         
31         return isValidBSThelp(root->left, min, root) &&
32             isValidBSThelp(root->right, root, max);
33     }
34     bool isValidBST(TreeNode* root) {
35         return isValidBSThelp(root, nullptr, nullptr);
36     }
37 };
原文地址:https://www.cnblogs.com/habibah-chang/p/13757782.html