Algorithm 如果为每个节点指定了父指针,则查找树的直径

Algorithm 如果为每个节点指定了父指针,则查找树的直径,algorithm,binary-tree,Algorithm,Binary Tree,我在这里搜索了这个问题,但没有看到任何关于二叉树的优化直径的问题 How do we find diameter of a binary tree if parent pointer to each node is given. Definition of tree diameter is : Longest distance between two nodes of tree. 编辑::请使用父指针查找直径。我知道 使用递归查找直径,这是通过查找 (树的左直径、右直径和高度) 节点结构如下

我在这里搜索了这个问题,但没有看到任何关于二叉树的优化直径的问题

How do we find diameter of a binary tree if parent pointer to each node is given.

Definition of tree diameter is : Longest distance between two nodes of tree.
编辑::请使用父指针查找直径。我知道 使用递归查找直径,这是通过查找 (树的左直径、右直径和高度)

节点结构如下 类节点{ 左淋巴结; 节点权; 节点父指针; int数据

}这段代码显示了如何计算二进制时间的直径,单位为O(n)

然而,不需要家长指针,所以我可能误解了你的问题

/*The second parameter is to store the height of tree.
   Initially, we need to pass a pointer to a location with value
   as 0. So, function should be used as follows:

   int height = 0;
   struct node *root = SomeFunctionToMakeTree();
   int diameter = diameterOpt(root, &height); */
int diameterOpt(struct node *root, int* height)
{
  /* lh --> Height of left subtree
      rh --> Height of right subtree */
  int lh = 0, rh = 0;

  /* ldiameter  --> diameter of left subtree
      rdiameter  --> Diameter of right subtree */
  int ldiameter = 0, rdiameter = 0;

  if(root == NULL)
  {
    *height = 0;
     return 0; /* diameter is also 0 */
  }

  /* Get the heights of left and right subtrees in lh and rh
    And store the returned values in ldiameter and ldiameter */
  ldiameter = diameterOpt(root->left, &lh);
  rdiameter = diameterOpt(root->right, &rh);

  /* Height of current node is max of heights of left and
     right subtrees plus 1*/
  *height = max(lh, rh) + 1;

  return max(lh + rh + 1, max(ldiameter, rdiameter));
}

请澄清父指针与直径的关系。如果将“直径”定义为任意两个节点之间的最大距离,则与指定的父节点无关。另一方面,如果存在区别,例如父节点是源节点,其他节点是排水管,那么您可能要查找从任何节点到源的最大距离,而不是树的直径

也就是说,您可以通过运行广度优先搜索(BFS)来解决这两个问题。如果要查找与专用父节点的距离,请运行BFS,并用到父节点的距离标记每个节点

另一方面,如果要查找树直径运行BFS两次:第一次从您喜欢的任何节点开始,并找到最远的节点;然后从最远的节点开始,找到离它最远的节点。碰巧的是,从“距离任何给定节点最远的节点”到“距离刚找到的最远节点最远的节点”的距离给出了树的直径。

假设给定了指向树的任何节点的指针

在给定节点上执行BFS(广度优先搜索),并找到距离给定节点最大的节点。与给定节点有最大距离的节点将是叶节点。我们称之为node1
现在再次在节点1上应用BFS,并找到任何节点与节点1的最大距离。这个距离就是树的直径。因为node1是树的一个叶子,BFS会找到从node1(叶子)到树中所有其他节点的最短距离。显然,距离节点1最远的节点将是一片叶子,因此我们将得到树的直径。

对不起,我应该在问题中提到这一点,必须使用父指针。我现在已经编辑了这个问题。你可以使用父指针来重建O(n)中的左指针和右指针,然后使用原始算法?你说父指针是什么意思?你有所有叶子的清单吗?这不是一个非常合乎逻辑的数据结构。。。