繁体   English   中英

广度优先树

[英]Breadth-first tree

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

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

树的结构应该是这样的:

    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;

}

如果使用递归,则肯定是“深度优先”的实现,对于广度优先的搜索,则使用队列或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
}

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


例如:使用阵列nodes[the amount of node]0th Node是A (number begin zero)时,数n节点的是even像C( n=2 ),那么节点[(N-2)/ 2]。 right = nth node否则像B一样odd然后是nodes [(n-1)/ 2]。left= nth node

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM