天梯赛 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");
        }
    }
}
相关推荐
小鸡吃米…2 小时前
基准测试与性能分析
开发语言·python
神仙别闹2 小时前
基于MATLAB实现(GUI)汽车出入库识别系统
开发语言·matlab·汽车
今儿敲了吗2 小时前
python基础学习笔记第一章
开发语言·python
badhope2 小时前
C语言二级考点全解析与真题精讲
c语言·开发语言·c++·人工智能·python·microsoft·职场和发展
沐苏瑶2 小时前
Java 数据结构精讲:二叉树遍历算法与底层实现剖析
数据结构·算法
JMchen1232 小时前
跨技术栈:在Flutter/Compose中应用自定义View思想
java·经验分享·flutter·canvas·dart·自定义view
黄昏晓x2 小时前
C++11
android·java·c++
醉酒柴柴2 小时前
word创建样式以后应用于所有新文件
开发语言·学习·c#·word
董董灿是个攻城狮2 小时前
大模型连载8:词向量如何表示近义词?
人工智能·python·算法·机器学习