天梯赛 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");
        }
    }
}
相关推荐
Dicky-_-zhang1 小时前
系统容量规划与压测实战:从1万到100万QPS的科学扩容
java·jvm
BirdenT1 小时前
20260519紫题训练
c++·算法
Highcharts.js6 小时前
倒置百分比堆叠面积图表示列详解|Highcharts大气成分图表代码
开发语言·信息可视化·highcharts·图表开发·面积图·图表示例·推叠图
csdn_aspnet6 小时前
C语言 Lomuto分区算法(Lomuto Partition Algorithm)
c语言·开发语言·算法
Dicky-_-zhang6 小时前
消息队列Kafka/RocketMQ选型与高可用架构:从单体到100万TPS的演进
java·jvm
晨曦中的暮雨6 小时前
4.15腾讯 CSIG云服务产线 一面
java·开发语言
存在morning7 小时前
【GO语言开发实践】二 GO 并发快速上手
大数据·开发语言·golang
fake_ss1987 小时前
AI时代学习全栈项目开发的新范式
java·人工智能·学习·架构·个人开发·学习方法
谙弆悕博士7 小时前
【附C源码】从零实现C语言堆数据结构:原理、实现与应用
c语言·数据结构·算法··数据结构与算法
茉莉玫瑰花茶7 小时前
工作流的常见模式 [ 1 ]
java·服务器·前端