java - 从层序(BFS 序)构建 BST

标签 java binary-search-tree breadth-first-search

我尝试根据给定的级别顺序(BFS 顺序)构造 BST。我知道这是可能的,但我不知道我该怎么写。问题是我必须使用 BFS 序列。所以,我不能在这里使用递归,我必须迭代地编写我的程序......我发现这有点令人困惑。

我尝试这样做:

public static TreeNode constructBFSTree(ArrayList<Integer> bfs) {
    if (bfs== null) return null;
    ArrayList<TreeNode> result = new ArrayList<TreeNode>();
        for (int i = 0; i < bfs.size()-1; i ++){
             TreeNode node = result.get(i);
             int leftValue = (bfs.get(i+1)!=null)? bfs.get(i+1) : Integer.MAX_VALUE ;
             int rightValue = (bfs.get(i+2)!=null)? bfs.get(i+2) : Integer.MIN_VALUE;

             node.left = (leftValue <= node.data)? new TreeNode(leftValue) : null;
             node.right = (rightValue > node.data)? new TreeNode(rightValue) : null;
             result.add(node);
        }

        return result.get(0);
    }

本地 ArrayList 在这里并不重要。我只是将它添加到“捕获”第一个节点,该节点是我应该返回的构造树的根。问题是我只能得到根及其子项。

如何编写这个程序?

最佳答案

你试试下面的代码怎么样? (注意:我没有测试它,因为您没有提供类定义。但它应该会插入您走向正确的方向。)

我对 TreeNode 类的假设是,它的构造函数采用一个整数,并将 leftright 指针初始化为 。例如:

class TreeNode {
    TreeNode left;
    TreeNode right;
    int key;
    public TreeNode(int key) {
        this.key = key;
        this.left = null;
        this.right = null;
    }
}

该函数的代码如下:

public static TreeNode constructBFSTree(ArrayList<Integer> bfs) {
    if (bfs == null || bfs.isEmpty()) {
        return null;
    }

    Queue<TreeNode> q = new Queue<TreeNode>();
    TreeNode root = new TreeNode(bfs.get(0));
    q.add(root);
    int i = 1;
    while (!q.isEmpty() && i < bfs.size()) {
        TreeNode currentNode = q.poll();
        currentNode.left = new TreeNode(bfs.get(i++));
        q.add(curentNode.left);
        if (i < bfs.length()) {
            currentNode.right = new TreeNode(bfs.get(i++));
            q.add(currentNode.right);
        }
    }
    return root;
}

关于java - 从层序(BFS 序)构建 BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37185124/

相关文章:

c - 平衡 BST 与四种情况 RR LL LR RL

c - 如果图不是邻接矩阵的形式,如何找到节点的所有邻居?

algorithm - 您是在递归算法中以广度优先还是深度优先进行搜索?

python - 这是广度优先搜索算法吗?

java - 优先队列和优先阻塞队列

java - 如何使用 Java Web 启动仅下载一次的应用程序

java - android可能出现空指针异常

java - 使用spring配置jta事务管理器?

c - 删除二叉搜索树根节点的问题

java - 如何在java中对带有键和值的未排序数组使用二分搜索?