首页 > 其他 > 详细

19.3.2 [LeetCode 98] Validate Binary Search Tree

时间:2019-03-02 12:16:46      阅读:176      评论:0      收藏:0      [点我收藏+]

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node‘s key.
  • The right subtree of a node contains only nodes with keys greater thanthe node‘s key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

Input:
    2
   /   1   3
Output: true

Example 2:

    5
   /   1   4
     /     3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node‘s value
             is 5 but its right child‘s value is 4.
技术分享图片
 1 class Solution {
 2 public:
 3     bool minmax(TreeNode*root,pair<int,int>&ret) {
 4         if (root->left == NULL && root->right == NULL) {
 5             ret.first = root->val, ret.second = root->val;
 6             return true;
 7         }
 8         int min=root->val, max=root->val;
 9         if (root->left) {
10             if (minmax(root->left, ret) == false)
11                 return false;
12             if (ret.second >= root->val)
13                 return false;
14             min = ret.first;
15         }
16         if (root->right) {
17             if (minmax(root->right, ret) == false)
18                 return false;
19             if (ret.first <= root->val)
20                 return false;
21             max = ret.second;
22         }
23         ret.first = min, ret.second = max;
24         return true;
25     }
26     bool isValidBST(TreeNode* root) {
27         if (!root)return true;
28         pair<int, int>a;
29         return minmax(root,a);
30     }
31 };
View Code

 

19.3.2 [LeetCode 98] Validate Binary Search Tree

原文:https://www.cnblogs.com/yalphait/p/10460293.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!