搜索二叉树定义: 每一颗子树,左树都比节点小,右树都比节点大,无重复值。
中序遍历
依次递增就行
| 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; |
| |
| }else{ |
| preValue = head.value; |
| } |
| |
| 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; |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探