我有以下二进制树:
[Node1]
[Node2] [Node3]
[Node4][Node5] [Node6][Node7]
[...] [...]
每个节点都有唯一的id,节点分别存储“父”参数。
我需要的是获得不完整的第一个“父”(即没有2个子节点的节点);使用“first'parent'”我的意思是最接近根节点。
我尝试了一些循环,但总是得到相同的结果只循环一侧......
更新
这是无限的,我认为不确定它是DFS
答案 0 :(得分:1)
要查找满足条件的树中最浅的节点,您需要使用breadth first search。
它基本上看起来像这样一个片段,以语言无关的方式
q = empty queue
q.push(root)
while q is not empty
current = q.pop
if current meets condition
return current
for each child of current
q.push(child)
这应该可以用任何语言实现,确保q实际上是FIFO队列。
答案 1 :(得分:0)
我结合这两个功能得到了理想的结果:
function traverseTree( $id, $level=0 ) {
static $depths = array();
$depth++;
$c = get_comments( array( 'type' => 'member', 'parent' => $id ) );
if( count( $c ) < 2 ) {
$depths[$id] = $level;
}
if( isset( $c[0] ) )
traverseTree( $c[0]->comment_ID, $level+1 );
if( isset( $c[1] ) )
traverseTree( $c[1]->comment_ID, $level+1 );
return $depths;
}
function depthChoose( $depths ) {
return min( array_keys( $depths, min( $depths ) ) );
}
所以depthChoose( traverseTree( $id ) );
做了工作。
注意:$ c [0]与node-&gt; left相同,$ c [1] as node-&gt; right;