简体   繁体   中英

Binary search tree level order with parent node

Hi I am trying to print out level order of a binary search tree in the format (node element, parent node element) . I am currently using queues to get the level order but I am having a hard time getting the parent node. Is it possible to do with queues? If so how would I go about doing it? If not what is a more optimal way of doing it? Thank you!

For example with the following tree:

         6
       /   \
      5     7

Level 0: (6, null)

Level 1: (5, 6) (7, 6)

So unfortunately there isn't a way of doing this strictly with one queue, assuming your nodes only have a left,right, and value. The problem is once you get to depths > 0, the nodes at that level might have different parents, and that information is gone unless you store it in some fashion.

The easy way to do this is to just add a Node parent inside of your Node class. Barring that, you could also make a inner class that holds the mapping of the Node to parent node, or you could use any number of data structures. Below I included how to do this with hashmaps.

public void printLevelOrder(){
    Queue<Node> q = new LinkedList<Node>();
    Map<Node, Node> parents = new HashMap<Node,Node>();
    Node nextLevel = null;
    q.add(this);
    int lvl = 0;

    while (!q.isEmpty()){
        Node n = q.remove();
        if (n == nextLevel || nextLevel == null){
            System.out.print("\nlvl " + lvl++ +" ");
            nextLevel = null;
        }
        System.out.print("("+n.value +","+parents.remove(n)+")");
        if (n.left != null){
            q.add(n.left);
            parents.put(n.left, n);
            if (nextLevel == null)
                nextLevel = n.left;
        }
        if (n.right != null){
            q.add(n.right);
            parents.put(n.right, n);
            if (nextLevel == null)
                nextLevel = n.right;
        }
    }
}

To print the nodes by level I do the following. The next level is determined by adding the first non null nextLevel node. When we have reached that node, we know we are at the start of the next line, and null it out again.

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