• Validate Binary Search Tree

Validate Binary Search Tree

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.

这题需要判断是不是一个正确的二叉搜索树,比较简单地一道题。 我们通过递归整棵树来解决,代码如下: 1. class Solution { 2. public: 3. bool isValidBST(TreeNode root) { 4. return valid(root, numeric_limits::min(), numeric_limits::max()); 5. } 6. 7. bool valid(TreeNode node, int minVal, int maxVal) { 8. if(!node) { 9. return true; 10. } 11. 12. if(node->val <= minVal || node->val >= maxVal) { 13. return false; 14. } 15. 16. return valid(node->left, minVal, node->val) && 17. valid(node->right, node->val, maxVal); 18. } 19. };