《編程之美》 3.8 求二叉樹節點中的最大距離
問題:如果把二叉樹看成一個圖,並且父子結點之間的連線看成是雙向的,姑且定義“距離”爲兩個結點之間邊的個數,求一棵二叉樹中相距最遠的兩個結點之間的距離。
解法一:詳見《編程之美》3.8以及代碼。
代碼一:
typedef struct BinTreeNode
{
char data;
int nMaxLeft;
int nMaxRight;
BinTreeNode *lchild,*rchild;
};
/*------------------------------------------------------------------------*/
void FindMaxDist(BinTreeNode *pRoot)
{
if (pRoot == NULL) {
return;
}
if (pRoot->lchild == NULL) {
pRoot->nMaxLeft = 0;
}
if (pRoot->rchild == NULL) {
pRoot->nMaxRight = 0;
}
if (pRoot->lchild != NULL) {
FindMaxDist(pRoot->lchild);
}
if (pRoot->rchild != NULL) {
FindMaxDist(pRoot->rchild);
}
if (pRoot->lchild != NULL) {
int nTempMax = 0;
if (pRoot->lchild->nMaxLeft > pRoot->lchild->nMaxRight) {
nTempMax = pRoot->lchild->nMaxLeft;
}
else {
nTempMax = pRoot->lchild->nMaxRight;
}
pRoot->nMaxLeft = nTempMax + 1;
}
if (pRoot->rchild != NULL) {
int nTempMax = 0;
if (pRoot->rchild->nMaxLeft > pRoot->rchild->nMaxRight) {
nTempMax = pRoot->rchild->nMaxLeft;
}
else {
nTempMax = pRoot->rchild->nMaxRight;
}
pRoot->nMaxRight = nTempMax + 1;
}
if (pRoot->nMaxLeft + pRoot->nMaxRight > nMaxLen) {
nMaxLen = pRoot->nMaxLeft + pRoot->nMaxRight;
}
}
/*-------------------------------------------------------------------------*/
解法二:使用最基本的二叉樹結點的定義,詳見《[編程之美]求二叉樹中節點的最大距離》。
代碼二:
#include <stdio.h>
#include <stdlib.h>
#include <stack>
using namespace std;
typedef struct BinTreeNode * BinTree;
typedef struct BinTreeNode
{
char data;
BinTreeNode *lchild,*rchild;
};
int MaxDistanceBetweenNodes(BinTreeNode *pRoot,int *pmax)
{
// return 0 if leaf node
if (pRoot->lchild == NULL && pRoot->rchild == NULL) {
return 0;
}
// depth of two sub-trees
int ldepth = 0;
int rdepth = 0;
if (pRoot->lchild != NULL) {
ldepth = 1 + MaxDistanceBetweenNodes(pRoot->lchild,pmax);
}
if (pRoot->rchild != NULL) {
rdepth = 1 + MaxDistanceBetweenNodes(pRoot->rchild,pmax);
}
if (ldepth + rdepth > *pmax) {
*pmax = ldepth + rdepth;
}
return ldepth > rdepth ? ldepth : rdepth;
}
int MaxDistanceInBinTree(BinTreeNode *pRoot,int *pmax)
{
if (pRoot == NULL || pmax == NULL) {
return -1;
}
*pmax = 0;
return MaxDistanceBetweenNodes(pRoot,pmax);
}
void buildBinTree(BinTree *T,char *str)
{
stack<BinTree> s;
*T = NULL;
BinTree p,t;
p = t = NULL;
int i,k;
i = 0;
while(str[i])
{
switch(str[i]){
case '(': s.push(p); k = 1; break;
case ')': t = s.top(); s.pop(); break;
case ',': k = 2; break;
default:
p = new BinTreeNode;
p->data = str[i];
p->lchild = p->rchild = NULL;
if (*T == NULL){
*T = p;
}
else if (k == 1){
t = s.top();
t->lchild = p;
}
else {
t = s.top();
t->rchild = p;
}
}
i++;
}
}
int main()
{
BinTree T;
char *t = "A(B(C,D),E(F,))";
buildBinTree(&T,t);
int *pmax = (int *)malloc(sizeof(int));
printf("Max Distance : %d %d.\n",*pmax,MaxDistanceInBinTree(T,pmax));
free(pmax);
}
測試輸出:
Max Distance : 4 2.
REF:
1,《編程之美》 3.8 求二叉樹中結點的最大距離
2,http://blog.csdn.net/lalor/article/details/7626678