Binary search tree level order with parent node

梦想的初衷 提交于 2019-12-24 09:24:35

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/16350038/binary-search-tree-level-order-with-parent-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!