Validate Binary Search Tree

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.

思路

递归,对于每个根节点,判断左右子节点是否在规定的大小区间内,然后再判断两个子树是否是合法的。

 1     bool isValid(TreeNode *root, int min, int max){
 2         if(root == NULL)
 3             return true;
 4         if(root->val <= min || root->val >= max)
 5             return false;
 6         return isValid(root->left, min, root->val)&&isValid(root->right, root->val, max);
 7     }
 8     bool isValidBST(TreeNode *root) {
 9         // Note: The Solution object is instantiated only once and is reused by each test case.
10         if(root == NULL)
11             return true;
12         return isValid(root->left, INT_MIN, root->val)&&isValid(root->right, root->val, INT_MAX);
13     }

 

posted on 2013-10-16 20:23  waruzhi  阅读(156)  评论(0编辑  收藏  举报

导航