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.
Method 1: Based on the binary search tree, sequential traversal is a feature of an incremental sequence. During a sequential query, if the value of a node is larger than that of its first-ordered node, this is invalid.
class Solution {public: bool isValidBST(TreeNode* root,TreeNode*& pre) { if(!root)return true; bool flag = isValidBST(root->left,pre); if(!flag)return false; if(pre && pre->val >= root->val)return false; pre = root; return isValidBST(root->right,pre); } bool isValidBST(TreeNode* root) { TreeNode* pre = NULL; return isValidBST(root,pre); }};
Method 2: according to the definition of the Binary Search Tree, each node is in the middle of the left and right subtree values. Therefore, each recursive traversal gives a range of values, this range is the two boundary of the current subtree value. This range is used to determine validity. This method is more efficient than the method.
Struct treenode {int val; treenode * left; treenode * right; treenode (int x): Val (x), left (null), right (null ){}}; class solution {public: bool isvalidbst (treenode * root, int minvalue, int maxvalue) // range of left and right subtree {If (! Root) return true; If (minvalue <root-> Val & root-> Val <maxvalue) {return isvalidbst (root-> left, minvalue, root-> Val) & isvalidbst (root-> right, root-> Val, maxvalue);} return false;} bool isvalidbst (treenode * root) {return isvalidbst (root, int_min, int_max );}};
Leetcode validate Binary Search Tree