Diameter of Binary tree

static int tree_height(const Node* root, int& max_distance)

{

  const int left_height  = root->left  ? tree_height(root->left,  max_distance)  + 1 : 0;

  const int right_height = root->right ? tree_height(root->right, max_distance)  + 1 : 0;

  const int distance = left_height + right_height;

  if (max_distance < distance) max_distance = distance;

  return (left_height > right_height ? left_height : right_height);

}

 

int tree_diameter(const Node* root)

{

  int max_distance = 0;

  if (root) tree_height(root, max_distance);

  return max_distance;

}

这种思路很简单,再求Height的时候顺便求出每个Node的左右子树的Height的最大值

posted @ 2013-09-17 23:07  一只会思考的猪  阅读(175)  评论(0编辑  收藏  举报