【发布时间】:2016-03-23 18:13:51
【问题描述】:
4 0 2
0 1
0 3
2 3
0
3
我正在努力寻找解决上述问题的有效方法。
给定输入的第一行是:number of nodes in binary tree=4,root=0,depths=2
边或边上的节点没有按任何特定顺序给出,但将节点连接到左子节点的边出现在输入中。
最后两行查找0和3的位置,其输出为
1 2
3 1
树可以有超过百万个节点并使用
我找不到如何以可以找到节点坐标的方式表示树
更新代码
class node:
def __init__(self, x):
self.x=4
self.l=2
self.r=0
self.id=id
def recurse(node,id, depth = -1, position=-1, max_depth=-1):
depth=depth+1
current_depth=depth
max_depth=max(max_depth,current_depth)
matchl=False
matchr=False
if node.l :
(depthl,position,max_depth,matchl)=node.recurse(node.l,id,current_depth,position,max_depth)
positionl = position
position = position + 1
current_position=position
if node.r:
(depth,position,max_depth,matchr)=node.recurse(node.r,id,current_depth,position,max_depth)
if matchl:
return (depthl,positionl,max_depth,True)
if node.x==id:
return (current_depth,current_position,max_depth,True)
return (depth,position,max_depth,matchr)
n2=node(2)
n3=node(3)
n1=node(1)
n0=node(0)
n0.l=n1
n0.r=n3
n3.l=n2
(depth,position,max_depth,match)=node.recurse(n0,3)
if match:
answer = (position, max_depth - depth )
【问题讨论】:
-
为什么连接0到3的边的长度比连接0到1的边长?如果所有边的长度相等,我想我有一个解决方案,但是如果它们可以有不相等的长度,您能否准确说明哪些标准允许这种不等长的边?
-
这些边不相等是因为节点3有一个子节点,节点2,导致了网格的扩展
标签: python algorithm binary-tree