98 Validate Binary Search Tree
Links: https://leetcode.com/problems/validate-binary-search-tree/
Problem Description:
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 is binary search trees.
The topic requires verifying whether a tree is a two-fork search tree. Look at the definition of a binary search tree:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;(3)左、右子树也分别为二叉排序树;(4)没有键值相等的节点。
Clear definition then you can begin to do the problem, first of all the value of a node must have a value range, if the node is the parent node of the left subtree then the value of this node must be less than the parent node value, if the node exists in the right subtree of a node, then the value of the node must be greater than the node value.
class Solution {public: bool isValidBST(TreeNode* root) { return mValidBST(root, INT_MAX, INT_MIN); } bool mValidBST(TreeNode* root,int max,int min) { if(root==NULL) return true; if(root->val>max||root->val<min) return false; if((root->val==INT_MIN&&root->left!=NULL)||(root->val==INT_MAX&&root->right!=NULL)) return false; return mValidBST(root->left,root->val-1,min)&&mValidBST(root->right,max,root->val+1); }};
There is also a procedure is the middle sequence traversal tree, the binary search tree in the middle sequence traversal results must be an incremental sequence.
class Solution {public: bool isValidBST(TreeNode* root) { vector<int> num; minordertraversal(root,num); for(int i=0;i<(int)num.size()-1;i++) if(num[i]>=num[i+1]) return false; return true; } void minordertraversal(TreeNode* root,vector<int> &r) { if(root!=NULL) { minordertraversal(root->left,r); r.push_back(root->val); minordertraversal(root->right,r); } }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
98Validate Binary Search Tree