求二叉樹中節點的最大距離

2021-06-27 22:48:03 字數 957 閱讀 5018

如果我們把二叉樹看成乙個圖,

父子節點之間的連線看成是雙向的,

我們姑且定義"距離"為兩節點之間邊的個數。

寫乙個程式,

求一棵二叉樹中相距最遠的兩個節點之間的距離。

#include "stdlib.h"

#include "stdio.h"

typedef struct btnode

btnode;

btnode *createtree(int pre, int in, int l1, int r1, int l2, int r2)

} s->data = in[i];

s->lnode = createtree(pre, in, l1+1, l1+i-l2, l2, i-1);

s->rnode = createtree(pre, in, l1+i-l2+1, r1, i+1, r2);

return s;

}void preprint(btnode *p)

}void inprint(btnode *p)

}void finddepth(btnode *p, int depth, int &maxdepth)

finddepth(p->lnode, depth, maxdepth);

finddepth(p->rnode, depth, maxdepth);

--depth; }}

void main();

int in = ;

btnode *p;

p = createtree(pre, in, 0, 7, 0, 7);

int depth = 0;

int maxdepth = 0;

finddepth(p, depth, maxdepth);

printf("maxdepth = %d\n", maxdepth);

}

求二叉樹中節點的最大距離

遞迴求解,最大距離總是在一下兩種情況產生 情況1 最大路徑經過root 這個例子中,最長路徑經過root,其距離等於左子樹的高度 1 右子樹的高度 1 在這種情況下 如果只有左子樹,右子樹為空 最大距離 左子樹的高度 1 如果只有右子樹,左子樹為空 最大距離 右子樹的高度 1 如果既有右子樹,又有左...

求二叉樹中節點的最大距離

2010 10 26 16 03 37 分類 資料結構與演算法 標籤 proot 節點pleft pright nmaxleft 字型大小 大中小訂閱 如果我們把二叉樹看成乙個圖,父子節點之間的連線看成是雙向的,我們姑且定義 距離 為兩個節點之間邊的個數。寫乙個程式求一顆二叉樹中相距最遠的兩個節點之...

求二叉樹中節點的最大距離

如果我們把二叉樹看成乙個圖,父子之間的連線看成,姑且定義 距離 為兩個之間邊的個數。求一顆二叉樹中相距最遠兩個點之間的距離。struct node bittree int nmaxlen 0 void findmaxlen node proot if proot pleft null if proo...