![](/img/trans.png)
[英]Given a binary tree, find the horizontal distance between 2 nodes at the same level, also counting the position where the node is not present
[英]Find position of nodes in binary tree
我正在尝试找到以下问题的有效解决方案。 给定输入为:二叉树中的节点数,根,边和一些节点的列表,以在树中绘制它们的坐标(如果它是在网格中绘制的),例如 边缘或边缘上的节点的顺序没有指定,但是将节点连接到左孩子的边缘在输入中出现得较早。 树可以拥有超过一百万个节点,并使用
class Node {
public Node left;
public Node right;
public int key;...}
太慢了。 但是我找不到如何以可能找到节点坐标的方式表示树。 输入示例:
4 0 // 4 is number of nodes, 0 is root
0 1 // edge
0 3 // edge
2 3 // edge
我应该找到节点的坐标,例如3
,输出将是: 3 1
您将需要构建整个树,因为您需要知道树的结构才能确定X坐标。
但是,如果您的算法是线性的 ,那么即使有数百万个节点也不是问题。
该算法看起来非常简单。
首先,我们需要构建树结构。 在构建树以快速访问特定Node
时Map<Integer, Node>
我将使用Map<Integer, Node>
(该映射稍后也会有用)。(或者,如果Node
id是范围为0..NodeCount-1
整数,则即使Node[]
也可以正常工作) 0..NodeCount-1
)
Node
类应具有便捷方法addNode(Node node)
,该方法首先添加left
Node,然后添加right
Node。 它可能看起来像这样:
void addNode(Node node) {
if (left == null)
left = node;
else
right = node;
}
关于addEdge(int from, int to)
方法,这样的事情应该可以工作
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);
}
然后,我们需要将X坐标分配给节点。 我将使用递归函数,如下所示:
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);
}
并这样称呼它
assignXY(rootNode, -1, maxDepth);
现在,所有节点都有X坐标,因此您只需从我们先前定义的Map
拉出您感兴趣的Node
,然后返回其x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.