LeetCode: Validate Binary Search Tree [detailed analysis], leetcodevalidate
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.
Let's review the definition of BST. the children and grandchildren of any node recursively meet the requirements. The children and grandchildren of the Left node are smaller than the node, and the children and the right node are larger than the node. If you judge this, it is OK. one idea: in a recursive program, it is not enough to judge that only one node is greater than the left son and less than the right son. In this way, the right son and the right son cannot be judged by errors, therefore, you need to change the node value to the Boundary Value and pass it down recursively. The Code is as follows:
Class Solution {public: bool isValidBST (TreeNode * root) {return check (root, INT_MIN, INT_MAX);} private: bool check (TreeNode * root, int left, int right) {if (root = NULL) return true; return (root-> val> left) & (root-> val <right) & check (root-> left, left, root-> val) & check (root-> right, root-> val, right);} // The left boundary of the left son is uploaded above, the node value is used in the right border, and the right son mirror is symmetric };
PS: Error code written according to the ideas mentioned above
/*** 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 isValidBST (TreeNode * root) {if (root = NULL) return true; bool bleft = true, bright = true; if (root-> left! = NULL) {if (root-> val> root-> left-> val) {// note that the root node cannot be larger than all the root nodes on the left due to the fact that, right son of the left son and left son of the right son; bleft = isValidBST (root-> left);} else {return false ;}} if (root-> right! = NULL) {if (root-> val <root-> right-> val) {bright = isValidBST (root-> right);} else {return false ;}} return bleft & bright ;}};