[算法分析与设计] leetcode 每周一题: Validate Binary Search Tree
来源:互联网 发布:mac os 10.12原版镜像 编辑:程序博客网 时间:2024/06/04 19:10
题目链接:https://leetcode.com/problems/validate-binary-search-tree/discuss/
题目:
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.
Example 1:
2 / \ 1 3Binary tree
[2,1,3]
, return true.Example 2:
1 / \ 2 3Binary tree
[1,2,3]
, return false.在二叉搜索树中每一个节点都可能存在约束,都有可能存在一个比该节点大的节点以及一个比该节点小的点,因此用递归,每次传入一个当前结点,极大点,极小点,比较即可。
代码:
class Solution {public: bool judgeValid(TreeNode * curNode, TreeNode* minNode, TreeNode* maxNode) { if(!curNode) return true; if(minNode && minNode->val >= curNode->val || maxNode && maxNode->val <= curNode->val){ return false; } return judgeValid(curNode->left, minNode, curNode) && judgeValid(curNode->right, curNode, maxNode); } bool isValidBST(TreeNode* root) { return judgeValid(root, nullptr, nullptr); }};
阅读全文