简体   繁体   中英

Find position of nodes in binary tree

I'm trying to find effective solution to the following problem. Given input is: number of nodes in binary tree, root, edges and list of some nodes to find their coordinates in tree if it was drawn in a grid,eg 在此处输入图片说明 Edges or nodes on the edge are not given in any specific order, but edge that connects node to left child appears earlier in input. Tree can have more than million nodes and build tree using

class Node {
public Node left;
public Node right;
public int key;...}

is too slow. But I can't find how to represent tree in such way that it would be possible to find coordinates of nodes. Example of input:

4 0 // 4 is number of nodes, 0 is root

0 1 // edge
0 3 // edge
2 3 // edge

And I should find coordinate of node eg 3 and output will be: 3 1

You will need to construct the whole tree, since you need to know the structure of the tree to be able to determine the X-coordinate.
However it shouldn't be a problem even with millions of nodes, if your algorithm is linear .

The algorithm seems pretty straightforward.

First we need to construct the tree structure. I would use a Map<Integer, Node> when building the tree to access a specific Node quickly (the map will be useful later as well).(or even a Node[] would work fine if the Node ids are integers in range 0..NodeCount-1 )
Node class should have a convenience method addNode(Node node) which first adds left Node and then the right Node. It could look like this:

void addNode(Node node) {
  if (left == null)
      left = node;
  else
      right = node;
}

Concerning addEdge(int from, int to) method, something like this should work

void addEdge(int from, int to) {
    Node fromNode = nodes.get(from); // this should never be null, root should be added manually first
    Node toNode = nodes.get(to);
    if (toNode == null) {
        toNode = new Node(to); // 'content' constructor
        nodes.put(to, toNode);
    }
    fromNode.addNode(toNode);
}

Then, we need to assign the X-coordinates to the Nodes. I would use a recursive function, something like this:

int assignXY(Node node, int lastX, int y) {
    node.y = y;
    node.x = 1 + (node.left == null ? lastX: assignX(node.left, lastX, y - 1));
    return (node.right == null ? node.x : assignX(node.right, node.x, y - 1);
}

And call it like this

assignXY(rootNode, -1, maxDepth);

Now, all Nodes have X-coordinates, so you can simply pull the Node you're interested in from the Map we defined earlier and return its x

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