【问题标题】:Breadth-first tree广度优先树
【发布时间】:2016-11-13 00:59:28
【问题描述】:

我似乎在构建广度优先树时遇到问题。

在下面的代码中,我有一个通过另一个类中的循环插入的节点。

树的结构应该是这样的:

    A
   / \
  B   C
 /\   /\
D E  F  G

现在是代码:

我的代码正确地构造了左侧,而右侧也添加了左侧。我了解代码中发生这种情况的位置,但是有没有办法防止这种情况发生?

public Node familyTree;

public void breadthFirst(Node newNode){
    familyTree = breadthFirst(familyTree,newNode);

}

public Node breadthFirst(Node T, Node newNode){
    if(T == null){
        T = newNode;
        return T;            
    }
    if(T.left == null){
        newNode.height = T.height + 1;            
        T.left = newNode;
        return T;
    }
    else if(T.right == null){
        newNode.height = T.height + 1;    
        T.right = newNode;
        return T;
    }
    else{            
         T.left = breadthFirst(T.left, newNode);
         T.right = breadthFirst(T.right, newNode); <-- this is the corporate           
    }
    return T;

}

【问题讨论】:

  • 你在递归思考。你应该反复思考。在进行广度优先时,使用“尚未评估”的节点队列。
  • 你在做一个depthFirstSearch的实现,如果你想做breathFirstSearch,使用队列。
  • 尝试建树,广度优先。

标签: java nodes breadth-first-search


【解决方案1】:

如果您使用递归,那么实现肯定是“深度优先搜索”,对于广度优先搜索,您使用队列或 FIFO 数据结构

伪代码

public Node breadthFirst(Node T, Node searchNode){
  Queue queue = new Queue();
  queue.queue(T);

  while (!queue.isEmpty()) {
    Node curNode = queue.dequeue();
    if (curNode == null) continue;

    if (curNode.value().equals(searchNode.value()) {
      return curNode;
    }

    queue.queue(curNode.left);
    queue.queue(curNode.right);
  } 

  return null; //or throw exception not found
}

【讨论】:

    【解决方案2】:

    我认为 breadth-first tree 类似于complete binary tree,因此您可以使用Array 来存储它而不是链接列表。关于complete binary tree,如果父号码是n,那么left number=2*n+1 right=2*n+2.


    例如:使用数组nodes[the amount of node] 0th Node 是 A(number begin zero) 当 Node 的数字 neven 时,如 C(n=2) 那么 nodes[(n-2)/2].right = nth node else odd like B then nodes[(n-1)/2].left = nth node

    【讨论】:

      【解决方案3】:

      您缺少的是使用左右节点的高度来确定当您到达 else 语句时新节点应该是哪一侧的子节点。目前,无论节点应放置在何处,您都将其添加到两侧。

      顺便说一句,看起来您可能会在高度属性中跟踪树的深度,而不是高度。这个stackoverflow 帖子很好地解释了差异。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-15
        • 2010-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多