查找树中节点的深度

时间:2019-10-18 00:28:14

标签: java recursion tree

我正在尝试编写一个返回非二叉树中节点深度的函数。在过去的几个小时里,我一直在努力,但是却一无所获,因此不胜感激。结果我不断得到1。我正在树中搜索与Person完全相同的实例。

/** 
 * Return the depth at which p occurs in this BugTree, 
 * or -1 if p is not in the BugTree.
 * Note: depth(root) is 0.
 * If p is a child of this BugTree, then depth(p) is 1. etc.
*/
public int depth(Person p) {
    if (root == p) return 0;
    if (childrenSize() == 0) return 0;
    int d= 0;
    for (BugTree c : children) {
        if (c.getRoot() == p) return 1;
        int k= c.depth(p);
        if (k != 1) {
            d= 1 + c.depth(p);
        } else {
            return d;
        }
    }

    return d;
}

3 个答案:

答案 0 :(得分:0)

从根节点开始进行级别订单遍历。让Node具有一个称为depth的属性。在“级别顺序遍历”中,添加子级时,将其深度作为父级的深度+1。“级别顺序遍历”使用队列数据结构,非常简单。

        1       Level 1 or 0
      2   3     Level 2 or 1
    4  5 6  7   Level 3 or 2

级别顺序遍历:1 2 3 4 5 6 7

算法:

LevelOrder(tree)

1) Create an empty queue q

2) temp_node = root; //with depth = 0    *start from root

3) Loop while temp_node is not NULL

    a) is temp_node the node needed? if yes print it's depth.

    b) Enqueue temp_node’s children (first left then right children) to q with child's depth = temp_node’s depth + 1

    c) Dequeue a node from q and assign it’s value to temp_node

结帐级别订单遍历:https://gist.github.com/yitonghe00/0b3ba3d3ad8dc008c1ebf30d0a9e8773V

答案 1 :(得分:0)

为节点的数据有效负载使用名称root会产生误导。 一棵 sorted 树可以比较,并选择合适的子树-更快。

public int depth(Person p) {
    if (data == p) { // data.equals(p)
        return 0;
    }
    for (BugTree c : children) {
        int d = c.depth(p);
        if (d != -1) {
            return 1 + d;
        }
    }
    return -1;
}

如您所见,它要简单得多。

答案 2 :(得分:0)

我建议您返回Optional<Integer>而不是使用带有特殊值(表示“未找到”)的int。即(IMO)更清晰,更不容易出错。使用Java流,解决方案如下所示:

public Optional<Integer> depth(Person person) {
    if (data.equals(person))
        return Optional.of(1);
    else
        return children.stream()
            .flatMap(ch -> ch.depth(person).stream())
            .findAny().map(d -> d + 1);
}

注意:我使用Optional<Integer>而不是OptionalInt来使用map方法。当然也可以使用OptionalInt,但是代码会稍微复杂一些。如果有人知道为什么特定类型的变体没有filtermap方法,我很想听听!