http://oj.leetcode.com/problems/validate-binary-search-tree/
判断一棵树是否为二叉搜索树。key 是,在左子树往下搜索的时候,要判断是不是子树的值都小于跟的值,在右子树往下搜索的时候,要判断,是不是都大于跟的值。很好的一个递归改进算法。
简洁有思想!
1 #include<climits> 2 3 // Definition for binary tree 4 struct TreeNode { 5 int val; 6 TreeNode *left; 7 TreeNode *right; 8 TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 }; 10 11 class Solution { 12 public: 13 bool subfunction(TreeNode *root,int min,int max) 14 { 15 if(root == NULL) 16 return true; 17 18 return (root->val>min && root->val < max &&subfunction(root->left,min,root->val) && subfunction(root->right,root->val,max)); 19 20 } 21 bool isValidBST(TreeNode *root) { 22 // Note: The Solution object is instantiated only once and is reused by each test case. 23 if(root ==NULL) 24 return true; 25 26 return subfunction(root,INT_MIN,INT_MAX); 27 28 } 29 };