LeetCode Validate Binary Search Tree

来源:互联网 发布:cf2.0优化 编辑:程序博客网 时间:2024/05/21 10:04

题目

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 than the node's key.
  • Both the left and right subtrees must also be binary search trees.

探测一个二叉树的合法性。

每个左子树上的点的值不能大于等于当前元素的值,每个右子树上的点的值不能小于等于当前值。

记录值的限制,递归调用即可。

 

代码:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:bool innerBST(TreeNode *root,long long min,long long max)//迭代扫描,根,可以取的最小合法值,可以取的最大合法值{if(root==NULL)//NULL为合法return true;if(root->left!=NULL&&(root->left->val>=root->val||root->left->val<=min))//左子树的值是否合法return false;if(root->right!=NULL&&(root->right->val<=root->val||root->right->val>=max))//右子树的值是否合法return false;if(innerBST(root->left,min,root->val)&&innerBST(root->right,root->val,max))//判断左右子树是否合法return true;return false;//否则不合法}    bool isValidBST(TreeNode *root) {        return innerBST(root,(long long)LONG_MIN-1,(long long)LONG_MAX+1);    }};


 

 

 

0 0