求二叉树节点的最大距离

有两种情况,要么是树的深度(例如链表的情况),要么是两个子树的深度和加2。最终的结果要么来自某个子树的最大距离,要么来自两个子树的深度和加2。

具体程序如下:

#include <stdio.h>
template<typename T>
class TreeNode {
 public:
  TreeNode() : left_(NULL), right_(NULL) { }
  TreeNode(const T& value) : value_(value), left_(NULL), right_(NULL) { }
  void LinkChild(TreeNode* left, TreeNode* right) {
    left_ = left;
    right_ = right;
  }
  T value_;
  TreeNode* left_;
  TreeNode* right_;
};
class VisitResult {
 public:
  VisitResult() {}
  VisitResult(int depth, int distance) : max_depth_(depth), max_distance_(distance) {}
  int max_depth_;
  int max_distance_;
};
template<typename T>
T Max(const T& a, const T& b) {
  if (a >= b) {
    return a;
  } else {
    return b;
  }
}
template<typename T>
VisitResult  FindMaxDistance(TreeNode<T>* current) {
  if (current) {
    VisitResult left_result = FindMaxDistance(current->left_);
    VisitResult right_result = FindMaxDistance(current->right_);
    VisitResult res;
    res.max_depth_ = Max(left_result.max_depth_ + 1, right_result.max_depth_ + 1);
    res.max_distance_ = Max(Max(left_result.max_distance_, right_result.max_distance_),
                            left_result.max_depth_ + right_result.max_depth_ + 2);
    return res;
  } else {
    VisitResult res(-1, 0);
    return res;
  }
}
int main(int argc, char** argv) {
  const int kNodeAmount = 7;
  TreeNode<int> tree[kNodeAmount];
  for (int i = 0; i < kNodeAmount; ++i) {
    tree[i].value_ = i;
  }
  tree[0].LinkChild(tree + 1, NULL);
  tree[1].LinkChild(NULL, tree + 4);
  tree[4].LinkChild(tree + 5, tree + 6);
  tree[5].LinkChild(tree + 2, tree + 3);
  VisitResult res =FindMaxDistance(tree);
  printf("%d\n", res.max_distance_);
}
      


参考文献:

编程之美3.8 P241

http://www.cnblogs.com/miloyip/archive/2010/02/25/1673114.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值