Saturday, September 14, 2013

Determine if a Binary Tree is a Binary Search Tree (BST) Brute force:

 3 properties:
1) left tree is BST, right tree is BST ;
2) root is smaller than all the elements in right tree
3) root is larger than all the elements in left tree 一开始想了这个方法



这样是错误的,不应该suppose 左树的最小是最左边的点

所以正确的brute force solution
 
bool isSubTreeLess(node *p,int val){
    if(p==NULL)
         return 1;
    else {
      return (p->dataleft,val)&&isSubtree(p->right,val);
    }
} 

bool isSubTreeLarge(node *p,int val){
    if(p==NULL)
         return 1;
    else {
      return (p->data>val)&&isSubTree(p->left,val)&&isSubtree(p->right,val);
    }
} 

bool isBST(node *root){
     if (!p) return true;
     return isTreeLess(p->left,root->data)&&isTreeLarge(p->right,root->data)&&isBST(root->left)&&isBST(root->right);
}
 

/////////////**********/////////////
isBST(node *p,int min,int max){
if(p->datadata>max){

       return (isBST(p->left,min,p->data)&&isBST(p->right,p->data,max);
}
else return 0;
}

isBST(node *root){
   return isBST(root,INT_MIN,INT_MAX);
}

/////////////**********/////////////
inorder traversal


No comments:

Post a Comment