天梯赛 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");
        }
    }
}
相关推荐
别或许1 小时前
1、高数----函数极限与连续(知识总结)
算法
田梓燊1 小时前
code 560
数据结构·算法·哈希算法
笨笨饿1 小时前
29_Z变换在工程中的实际意义
c语言·开发语言·人工智能·单片机·mcu·算法·机器人
kobesdu1 小时前
综合强度信息的激光雷达去拖尾算法解析和源码实现
算法·机器人·ros·slam·激光雷达
艾为电子2 小时前
【技术帖】让接口不再短命:艾为 C-Shielding™ Type-C智能水汽防护技术解析
c语言·开发语言
weixin_413063212 小时前
记录 MeshFlow-Online-Video-Stabilization 在线稳像
算法·meshflow·实时防抖
会编程的土豆2 小时前
【数据结构与算法】动态规划
数据结构·c++·算法·leetcode·代理模式
棉花骑士2 小时前
【AI Agent】面向 Java 工程师的Claude Code Harness 学习指南
java·开发语言
IGAn CTOU2 小时前
PHP使用Redis实战实录2:Redis扩展方法和PHP连接Redis的多种方案
开发语言·redis·php
炘爚2 小时前
深入解析printf缓冲区与fork进程复制机制
linux·运维·算法