Assume a BST is defined as follows:
class Solution { public: bool isValidBST(TreeNode *root) { return check(root, INT_MIN, INT_MAX); } private: bool check(TreeNode *root, int left, int right){ if(root == NULL) return true; return (root->val > left) && (root->val < right) && check(root->left, left, root->val) &&check(root->right, root->val, right); }//这里的左儿子的左界用上面传下来的,右界用节点值,右儿子镜面对称 };
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode *root) { if (root == NULL) return true; bool bleft = true, bright = true; if (root->left != NULL){ if (root->val > root->left->val){ //注意这里检验以及递归是不能保证根节点大于左边所有的,矛盾在于,左儿子的右儿子,以及右儿子的左儿子; bleft = isValidBST(root->left); } else{ return false; } } if (root->right != NULL){ if (root->val < root->right->val){ bright = isValidBST(root->right); } else{ return false; } } return bleft && bright; } };
LeetCode :: Validate Binary Search Tree[详细分析],布布扣,bubuko.com
LeetCode :: Validate Binary Search Tree[详细分析]
原文地址:http://blog.csdn.net/u013195320/article/details/37672351