1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A BOOLLeft (treenode* left,introot) { - while(Left->right! =NULL) { -left = left->Right ; the } - returnLeft->val <Root; - } - BOOLRight (treenode* right,introot) { + while(Right->left! =NULL) -right = Right->Left ; + returnRight->val >Root; A } at - BOOLIsvalidbst (treenode*root) { - if(Root = NULL)return true; - intleft =0, right =0; - BOOLLres =true, Rres =true; - if(Root->left) {//Non-empty case inleft =1; - if(Root->left->val >= Root->val)return false; toLres = Isvalidbst (root->Left ); + if(lres) Lres = Left (root->left,root->val);//If the left son is a legitimate binary tree, test the maximum value of the left son (that is, always take the left son's right son) is less than the root value - Else return false; the } * if(Root->right){ $right =1;Panax Notoginseng if(Root->right->val <= Root->val)return false; -Rres = Isvalidbst (root->Right ); the if(rres) Rres = right (root->right,root->val); + Else return false; A } the returnLres &&Rres; + } - $};
Legal binary Tree conditions: 1, the left son are small root, the right son is greater than the root 2, the left son, the right son are legitimate binary tree
Leetcode 98 Validate Binary Search tree to determine whether it is a legal binary