LeetCode 98. Validate Binary Search Tree

题意:给出头结点,让你判断这颗树是不是二叉搜索树。

思路:

  • 很显然,对于一棵二叉搜索树,其左右子树肯定也是二叉搜索树;
  • 因此,递归思路:如果左右子树都是BST,并且该根结点也符合规律(小于左子树的最小结点,小于右子树的最大结点)
  • 递归边界:如果是空节点,那么返回true;
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     // 得到值最大的结点
13     long long getMore(TreeNode* root){
14         if(root==NULL){
15             return -2333333333;
16         }
17         else{
18             TreeNode* tmp=root;
19             while(tmp->right!=NULL){
20                 tmp=tmp->right;
21             }
22             return tmp->val;
23         }
24     }
25     // 得到值最小的结点
26     long long getLess(TreeNode* root){
27         if(root==NULL){
28             return 2333333333;
29         }
30         else{
31             TreeNode* tmp=root;
32             while(tmp->left!=NULL){
33                 tmp=tmp->left;
34             }
35             return tmp->val;
36         }
37     }
38     
39     bool isValidBST(TreeNode* root) {
40         if(root==NULL){
41             return true;
42         }
43         long long v1=getMore(root->left);
44         long long v2=getLess(root->right);
45         return v1<root->val && v2>root->val && isValidBST(root->left) && isValidBST(root->right);
46     }
47 }; 
  • 我在实现的时候偷了一点懒;因为对于树结点val属性,在int的范围之内;因此我就使用long long和超过int范围的数来处理左右子树为空的情况(因为为空,肯定是符合二叉排序树的情况!)。

列出,在leetcode中,效率最高的代码:

思路很简单,BST的特点在于中序遍历是递增顺序的,因此使用非递归中序遍历,边遍历,边判断;如果中途发现不对,直接返回;

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isValidBST(TreeNode* root) {
13         stack<TreeNode*> s;
14         int pre = INT_MAX;
15         int f = 0;
16         while(!s.empty() || root)
17         {
18             while(root)
19             {
20                 s.push(root);
21                 root = root->left;
22             }
23             root = s.top();
24             s.pop();
25             if(f && root->val <= pre)
26                 return false;
27             pre = root->val;
28             f++;
29             root = root->right;
30         }
31         return true;
32     }
33     
34 };
原文地址:https://www.cnblogs.com/yy-1046741080/p/11618105.html