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.

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

思路:根据题目要求,实现三个方面判断,左子树、右子树以及左子树小于根节点,右子树大于根节点

java代码:

  1. public boolean isValidBST(TreeNode root) {
  2. if(root==null) return true;
  3. if(root.left == null && root.right == null) return true;
  4. boolean flag = isValidBST(root.left) && isValidBST(root.right);
  5. if(flag==false) return false;
  6. TreeNode left = root.left;
  7. if(left!=null) {
  8. while(left.right!=null) {
  9. left = left.right;
  10. }
  11. flag &= (left.val<root.val);
  12. }
  13. TreeNode right = root.right;
  14. if(right!=null) {
  15. while(right.left!=null) {
  16. right = right.left;
  17. }
  18. flag &= (right.val > root.val);
  19. }
  20. return flag;
  21. }

C++代码:

  1. bool isValidBST(TreeNode *root) {
  2. bool lflag=false;
  3. bool rflag=false;
  4. if(root==NULL || (root->left==NULL && root->right==NULL)) return true;
  5. if(isValidBST(root->left)) {
  6. TreeNode *p=root->left;
  7. while(p!=NULL && p->right!=NULL) {
  8. p=p->right;
  9. }
  10. if(p==NULL || p->val<root->val) lflag=true;
  11. }
  12. if(isValidBST(root->right)) {
  13. TreeNode *p=root->right;
  14. while(p!=NULL && p->left!=NULL) {
  15. p=p->left;
  16. }
  17. if(p==NULL || p->val>root->val) rflag=true;
  18. }
  19. if(lflag&&rflag) return true;
  20. return false;
  21. }
posted @ 2014-07-31 22:35  purejade  阅读(80)  评论(0编辑  收藏  举报