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.
思路:
给子树确定上下界,判断子树根节点值是否在上下界范围内,然后更新上下界。递归实现。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 isValidBST(TreeNode* root) { 13 if(!root) 14 return true; 15 if(judge(root->left,2,0,root->val)&&judge(root->right,1,root->val,0)) 16 return true; 17 return false; 18 } 19 20 bool judge(TreeNode*root,int flag,int a,int b)//flag=0,小于大于;flag=1,大于;flag=2,小于 21 { 22 if(!root) 23 return true; 24 if(flag==0) 25 { 26 if(!(root->val<b&&root->val>a)) 27 return false; 28 if(judge(root->left,0,a,root->val)&&judge(root->right,0,root->val,b)) 29 return true; 30 return false; 31 } 32 if(flag==1) 33 { 34 if(!(root->val>a)) 35 return false; 36 if(judge(root->left,0,a,root->val)&&judge(root->right,1,root->val,0)) 37 return true; 38 return false; 39 } 40 if(flag==2) 41 { 42 if(!(root->val<b)) 43 return false; 44 if(judge(root->left,2,0,root->val)&&judge(root->right,0,root->val,b)) 45 return true; 46 return false; 47 } 48 } 49 };