data structures - Given a tree check if it is a valid BST -


can please me going wrong logic? question given root of tree need tell if tree bst or not

the data value of every node in node's left subtree less data value of node. data value of every node in node's right subtree greater data value of node. given root node of binary tree, can determine if it's binary search tree?

boolean checkbst(node root) {   if(root.left==null && root.right==null)     return true;   if(root.left!=null) {     if(root.data<root.left.data)       checkbst(root.left);     else       return false;   }   if(root.right!=null) {     if(root.data>root.right.data)       checkbst(root.right);     else        return false;   }   return true; } 

your comparisons reversed. if valid bst, data in root should not less data in left subtree , value in root should not more data in right subtree.

also note in statement above have included equality - typically bst allows equal elements , can placed either on left or on right.

and last important point - if valid bst, root should not less nodes in left subtree. compare value root of left subtree. root of left subtree less notes in right subtree, nodes can potentially bigger original root. consider example:

    10    /   5  / \ 3   13 

according check valid bst, while not.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -