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 */ 10 class Solution { 11 public: 12 bool Left(TreeNode* left, int root){ 13 while(left->right != NULL){ 14 left = left->right; 15 } 16 return left->val < root; 17 } 18 bool Right(TreeNode* right,int root){ 19 while(right->left != NULL) 20 right = right->left; 21 return right->val > root; 22 } 23 24 bool isValidBST(TreeNode* root) { 25 if(root == NULL) return true; 26 int left = 0, right = 0; 27 bool lres = true,rres = true; 28 if(root->left){//不为空的情况下 29 left = 1; 30 if(root->left->val >= root->val) return false; 31 lres = isValidBST(root->left); 32 if(lres) lres = Left(root->left,root->val);//在左儿子是合法二叉树的情况下,检验左儿子的最大值(即一直取左儿子的右儿子)是否小于root值 33 else return false; 34 } 35 if(root->right){ 36 right = 1; 37 if(root->right->val <= root->val) return false; 38 rres = isValidBST(root->right); 39 if(rres) rres = Right(root->right,root->val); 40 else return false; 41 } 42 return lres && rres; 43 } 44 45 };
合法二叉树条件:1、左儿子均小于根,右儿子均大于根 2、左儿子、右儿子均为合法二叉树
时间: 2024-10-18 16:47:53