简体   繁体   English

根据级别顺序(BFS顺序)构造BST

[英]Construct a BST from level order (BFS order)

I tried to construct a BST from a given level order (BFS order). 我试图从给定的级别顺序(BFS顺序)构造一个BST。 I know it's possible but I don't know how can I write this. 我知道有可能,但我不知道该怎么写。 The problem, is that I had to work with the BFS sequence. 问题是,我必须使用BFS序列。 So, I can't use recursion here and I had to write my program itratively... And I find that a little confusing. 因此,我不能在这里使用递归,而不得不迭代地编写程序……而我发现这有点令人困惑。

I tried to do this : 我试图这样做:

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);
    }

The local ArrayList is not really important here. 本地ArrayList在这里并不是很重要。 I just add it to "catch" the first node which is the root of the constructed tree that I should return. 我只是将其添加到“捕获”第一个节点,该节点是我应该返回的构造树的根。 The problem is that I only get the root and its child. 问题是我只得到根及其子代。

How can I write this program? 如何编写该程序?

How about you try out the following code? 您如何尝试以下代码? (Note: I haven't tested it as you haven't provided the class definitions. But it should push you in the right direction.) (注意:由于您没有提供类定义,因此我没有对其进行测试。但这应该将您推向正确的方向。)

What I assume about the TreeNode class is that its constructor takes an integer and that it initializes the left and right pointers to null . 我认为对TreeNode类是它的构造函数需要一个整数,它初始化leftright指针null For example: 例如:

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

The code for the function could then be as follows: 该函数的代码如下:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM