天梯赛 L2-004 这是二叉搜索树吗?java

java 复制代码
import java.util.Scanner;

public class Main {
    static class Node {
        int val;
        Node left, right;
        Node(int x) { val = x; }
    }

    // 构建BST或其镜像,isMirror=true表示镜像
    private static Node buildBST(int[] pre, int start, int end, boolean isMirror) {
        if (start > end) return null;
        Node root = new Node(pre[start]);
        if (start == end) return root;

        int split = start + 1;
        if (!isMirror) {
            // 普通BST规则:左子树 < 根,右子树 >= 根
            while (split <= end && pre[split] < root.val) {
                split++;
            }
            // 验证右子树所有节点都 >= 根
            for (int i = split; i <= end; i++) {
                if (pre[i] < root.val) return null;
            }
        } else {
            // 镜像BST规则:左子树 >= 根,右子树 < 根
            while (split <= end && pre[split] >= root.val) {
                split++;
            }
            // 验证右子树所有节点都 < 根
            for (int i = split; i <= end; i++) {
                if (pre[i] >= root.val) return null;
            }
        }

        // 递归构建左右子树
        root.left = buildBST(pre, start + 1, split - 1, isMirror);
        if (root.left == null && (start + 1 <= split - 1)) return null;
        root.right = buildBST(pre, split, end, isMirror);
        if (root.right == null && (split <= end)) return null;
        return root;
    }

    // 后序遍历
    private static void postOrder(Node root, StringBuilder sb) {
        if (root == null) return;
        postOrder(root.left, sb);
        postOrder(root.right, sb);
        if (sb.length() > 0) sb.append(" ");
        sb.append(root.val);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] pre = new int[N];
        for (int i = 0; i < N; i++) {
            pre[i] = sc.nextInt();
        }
        sc.close();

        Node root = buildBST(pre, 0, N - 1, false);
        boolean isNormalBST = root != null;

        if (!isNormalBST) {
            root = buildBST(pre, 0, N - 1, true);
        }

        if (root != null) {
            System.out.println("YES");
            StringBuilder sb = new StringBuilder();
            postOrder(root, sb);
            System.out.println(sb);
        } else {
            System.out.println("NO");
        }
    }
}
相关推荐
CN-Dust5 分钟前
【C++专题】输出cout例题
开发语言·c++
叶落阁主5 分钟前
Spring Boot 4 实战:Jackson 2.x 升级到 3.x 踩坑全记录
java·后端·架构
布吉岛的石头6 分钟前
Java 中高级面试:JVM 内存模型 + GC 算法高频题总结
java·jvm·面试
时空系6 分钟前
第6篇:多维数据盒——管理大量数据 python中文编程
开发语言·python·ai编程
charlie1145141919 分钟前
嵌入式Linux驱动开发(7) 从虚拟设备到真实硬件 —— LED驱动硬件基础
linux·开发语言·驱动开发·内核·c
小短腿的代码世界18 分钟前
QCefView深度解析:Qt应用中嵌入Chromium浏览器的终极方案
开发语言·qt
2301_7926748626 分钟前
java学习(day32)
java
沉默-_-28 分钟前
备战蓝桥杯-哈希
c++·学习·算法·蓝桥杯·哈希算法
Reese_Cool29 分钟前
【STL】蓝桥杯/天梯赛终极杀器!10个C++字符串核心技巧,暴力破解高频考点
开发语言·c++·蓝桥杯·stl
摇滚侠30 分钟前
Oracle19c 导出 Oracle11g 导入,Oracle19c 导出导入,Oracle11g 导出导入
java·数据库·oracle