clllll  

搜索二叉树定义: 每一颗子树,左树都比节点小,右树都比节点大,无重复值。

中序遍历
依次递增就行

public static Integer preValue = Integer.MIN_VALUE;
public static boolean isBst(Node head){
if(head == null){
return true;
}
// 先遍历左子树
boolean isLeftBst = isBst(head.left);
if(!isLeftBst){
return false;
}
// 处理当前节点
if(head.value <= preValue){
//如果当前节点大于前一个值,就return false;
return false;
}else{
preValue = head.value; //更新preValue
}
//处理右子树
boolean isRightBst = isBst(head.right);
return isRightBst;
}

还有一种就是,中序遍历保存在数组中,然后for循环比较。

非递归方式

public static boolean isBstUnRecur(Node head) {
if (head == null) {
return true;
}
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty() || head != null) {
if (head.left != null) {
stack.push(head.left);
head = head.left;
} else {
head = stack.pop();
if (head.value <= preValue) {
return false;
} else {
preValue = head.value;
}
head = head.right;
}
}
return true;
}
posted on   llcl  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
 
点击右上角即可分享
微信分享提示