Coursera Algorithms week4 基础标签表 练习测验:Check if a binary tree is a BST

题目原文:

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 }

 

posted @ 2017-08-14 16:46  evasean  阅读(350)  评论(0编辑  收藏  举报