Diameter of Binary Tree

我怕爱的太早我们不能终老 提交于 2019-12-10 12:25:25

问题


"The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between any two nodes in the tree".

Will the C++ function below works for all cases to find the diameter of a binary tree? Called as s=0, and root = root of the binary tree

int helper(node *root,int &s){

  int l = 0, r = 0;

  if(root == NULL){
     return 0; 
  }
  l= helper(root->left,s);  //height of left subtree.
  r= helper(root->right,s); //height of right subtree.

  int mx_single=max(l,r)+1;
  int mx_top=max(mx_single,l+r+1);
  s=max(s,mx_top);
  return mx_single;
}

After returning to main, ans will be s.


回答1:


It looks wrong to me for many cases, but it would be helpful if your variable names were more descriptive. The function needs to return the diameter of the specified tree, but the recursive implementation also needs to use the height of each sub-tree.

Taking your definition of diameter to include the leaf nodes in the count, it can be reformulated recursively like so:

  • if the tree consists of a single node, then its diameter is 1. (The whole tree is a single-node path from one leaf node to itself).

  • if the root node of the sub-tree has exactly one child then its diameter is the diameter of the sub-tree rooted at that child. That follows because all the leaf nodes are in the subtree, therefore all the acyclic paths from leaf to leaf are confined to the subtree.

  • otherwise, the diameter is the greatest among the diameter of the left subtree, the diameter of the right subtree, and one plus the sum of the heights of the two subtrees (measured in nodes). This considers the possibilities that the longest leaf-to-leaf path is contained in the left subtree, is contained in the right subtree, or passes through the root. In the last case you don't need to identify the actual path; the subtree heights tell you how long it is (+ 1 node for the root).

Receiving the sub-tree heights to handle the third alternative appears to be the purpose of parameter s in your program, but you don't ever use it.

Your program will return the wrong result for a wide variety of trees, among them

  N
 /
1

(diameter 1, but your function will return 2)

  2
 / \
1   3

(diameter 3, but your function will return 2)

  3
 / \
2   4
 \
  1

(diameter 4, but your function will return 3)

  N
 / \
N   4
   / \
  3   5
 /   /
2   6
 \   \
  1   7

(diameter 7, but your function will return 5)

[In each figure, nodes along a path that measures the tree diameter are numbered, and all other nodes are designated 'N'.]

In fact, your function returns the height, counted in nodes, not the diameter. It looks like under favorable circumstances it may record the diameter in s, but not consistently.



来源:https://stackoverflow.com/questions/32957990/diameter-of-binary-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!