1. 程式人生 > >Coursera Algorithms week4 基礎標簽表 練習測驗:Check if a binary tree is a BST

Coursera Algorithms week4 基礎標簽表 練習測驗:Check if a binary tree is a BST

eth rmi tree eterm left div mine ont ret

題目原文:

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 }

Coursera Algorithms week4 基礎標簽表 練習測驗:Check if a binary tree is a BST