题目原文:
Given a binary tree where each ???????? contains a key, determine whether it is a binary search tree. Use extra space proportional to the height of the tree.
分析:
就是递归遍历BST,将每个节点x分别与x.left和x.right比大小。
1 public boolean isBST(BST<Key,Value> bst){ 2 return isBST(root); 3 } 4 private boolean isBST(Node x){ 5 if(x.left.key.compareTo(x.key) != -1) return false; 6 if(x.key.compareTo(x.right.key)!= -1) return false; 7 if(x.left != null ) return isBST(x.left); 8 if(x.right != null ) return isBST(x.right); 9 return true; 10 }
时间: 2024-10-10 19:58:06