Created
July 14, 2014 15:57
-
-
Save chouclee/27641529cf8c80d2bff4 to your computer and use it in GitHub Desktop.
[CC150][4.5] Implement a function to check if a binary tree is a binary search tree.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// traverse the tree in order | |
public class isBST<Key extends Comparable<Key>> { | |
private Node<Key> prev; | |
public boolean check(Node<Key> node) { | |
prev = null; | |
return isBst(node); | |
} | |
private boolean isBst(Node<Key> x) { | |
if (x == null) return true; | |
if (!isBst(x.left)) | |
return false; | |
if (prev != null && prev.key.compareTo(x.key) > 0) | |
return false; | |
prev = x; | |
System.out.println(prev.key); | |
return (isBst(x.right)); | |
} | |
public static void main(String[] args) { | |
isBST<Integer> test = new isBST<Integer>(); | |
Node<Integer> root = new Node<Integer>(0); | |
root.left = new Node<Integer>(2); | |
root.left.left = new Node<Integer>(1); | |
root.left.right = new Node<Integer>(3); | |
root.right = new Node<Integer>(6); | |
root.right.left = new Node<Integer>(5); | |
root.right.right = new Node<Integer>(8); | |
if (test.check(root)) | |
System.out.println("Yes"); | |
else System.out.println("No"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Node<Key> { | |
public Key key; | |
public Node<Key> left, right; | |
public Node(Key key) { | |
this.key = key; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment