编程之美之求二叉树中节点的最大距离

来源:互联网 发布:淘宝客返利网 赚钱 编辑:程序博客网 时间:2024/05/18 02:05

题目:如果我们把二叉树看成一个图,父子节点之间的连线看成是双向的,我们姑且定义"距离"为两节点之间边的个数。写一个程序求一棵二叉树中相距最远的两个节点之间的距离。

分析:树上分析的很清楚,计算一个二叉树的最大距离有两个情况:

1、 路径经过左子树的最深节点,通过根节点,再到右子树的最深节点。

2、 路径不穿过根节点,而是左子树或右子树的最大距离路径,取其大者。

但是书上的代码使用了额外的节点字段,这里给出我的代码,思路是一样的:

struct BinaryTree{int value;BinaryTree* left;BinaryTree* right;BinaryTree(int x):value(x),left(NULL),right(NULL){}};void findMaxLength(BinaryTree* root,int& depth,int& maxLength){if(root == NULL){depth = -1;maxLength = 0;return;}int ldepth,rdepth,lmaxLength,rmaxLength;findMaxLength(root -> left,ldepth,lmaxLength);findMaxLength(root -> right,rdepth,rmaxLength);depth = max(ldepth,rdepth)+1;maxLength = max(lmaxLength,rmaxLength);maxLength = max(maxLength,ldepth+rdepth+2);}int findMaxLength(BinaryTree* root){int depth=0,maxLength=0;findMaxLength(root,depth,maxLength);return maxLength;}


2 1
原创粉丝点击