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.
Confused what"{1,#,2,3}"Means? > Read more on how binary tree is serialized on OJ.
This is a difficulty: You must set the limit values on both sides of the node.I have absorbed the suggestions from the LeetCode Forum, instead of INT_MAX and INT_MIN. Here I use LLONG_MIN and LLONG_MAX.
If INT_MIN is used, when the value of the first left subtree is INT_MIN, it is regarded as false, which is actually true.
Although leetcode does not test this situation, sound programs are always the best.
Class Solution {public: bool isValidBST (TreeNode * root) {return validBST (root) ;}// Note: Do not forget the boundary on both sides: leftMax and rightMax settings/* I dont think it's a good idea to use int to represent the up and low bound of a TreeNode, INT_MIN and INT_MAX maybe used by TreeNode. we can use double or just the TreeNode itself. */bool validBST (TreeNode * root, long leftMax = LLONG_MIN, long rightMax = LLONG_MAX) {if ( ! Root) return true; if (! Root-> left &&! Root-> right) return true; if (root-> left & (root-> left-> val> = root-> val | root-> left-> val <= leftMax) return false; if (root-> right & (root-> right-> val <= root-> val | root-> right-> val> = rightMax) return false; return validBST (root-> left, leftMax, root-> val) & validBST (root-> right, root-> val, rightMax );}};