一,题目:
如果把二叉树看成一个图,父子节点之间的连线看成是双向的(无向图),定义"距离"为两节点之间边的个数。写一个程序,求一棵二叉树中相距最远的两个节点之间的距离。
二,思路
误导思路:不要以为求树的高度。
正确思路:求“图”中任意两个节点之间,相距最远的的两个节点之间的距离。
求解步骤:A,经过根节点,左边最深的点到右边最深的点的距离。
B,不经过根节点,而是左子树或右子树中最大距离,取其大者。
三,图解
情况A: 情况B:
A A
/ \/ \
B C B O
/ \ / \ / \
D E F G C D
/\
E F
/\
G H
情况A:最大距离经过顶点D-B-A-C-F(其中之一)
情况B:最大距离不经过顶点G-E-C-B-D-F-H(其中之一)
四,源码
#include "stdio.h" #include"stdlib.h" struct NODE { NODE* pLeft; // 左子树 NODE* pRight; // 右子树 int nMaxLeft; // 左子树中的最长距离 int nMaxRight; // 右子树中的最长距离 int chValue; // 该节点的值 }; int nMaxLen = 0; // 寻找树中最长的两段距离 void FindMaxLen(NODE* pRoot) { // 遍历到叶子节点,返回 if(pRoot == NULL) return; // 如果左子树为空,那么该节点的左边最长距离为0 if(pRoot -> pLeft == NULL) pRoot -> nMaxLeft = 0; // 如果右子树为空,那么该节点的右边最长距离为0 if(pRoot -> pRight == NULL) pRoot -> nMaxRight = 0; // 如果左子树不为空,递归寻找左子树最长距离 if(pRoot -> pLeft != NULL) FindMaxLen(pRoot -> pLeft); // 如果右子树不为空,递归寻找右子树最长距离 if(pRoot -> pRight != NULL) FindMaxLen(pRoot -> pRight); // 计算左子树最长节点距离 if(pRoot -> pLeft != NULL) { int nTempMax = 0; if(pRoot -> pLeft -> nMaxLeft > pRoot -> pLeft -> nMaxRight) { nTempMax = pRoot -> pLeft -> nMaxLeft; } else { nTempMax = pRoot -> pLeft -> nMaxRight; } pRoot -> nMaxLeft = nTempMax + 1; } // 计算右子树最长节点距离 if(pRoot -> pRight != NULL) { int nTempMax = 0; if(pRoot -> pRight -> nMaxLeft > pRoot -> pRight -> nMaxRight) { nTempMax = pRoot -> pRight -> nMaxLeft; } else { nTempMax = pRoot -> pRight -> nMaxRight; } pRoot -> nMaxRight = nTempMax + 1; } // 更新最长距离 if(pRoot -> nMaxLeft + pRoot -> nMaxRight > nMaxLen) { nMaxLen = pRoot -> nMaxLeft + pRoot -> nMaxRight; } } NODE *createTree() { NODE *root; int data; printf("input data:"); scanf("%d",&data); //printf("output data:%d\n",data); if(data==0) root=NULL; else/*根左右 前序建立二叉树*/ { root=(NODE*)malloc(sizeof(NODE)); root->chValue=data; root->pLeft=createTree(); root->pRight=createTree(); } return root; } int main() { NODE *root; root=createTree(); FindMaxLen(root); printf("%d",nMaxLen); return 0; }