简体   繁体   中英

Construct a BST from level order (BFS order)

I tried to construct a BST from a given level order (BFS order). 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. 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. 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 . 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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