Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the?longest?path between any two nodes in a tree. This path may or may not pass through the root.
1 diameter可能存在三個(gè)地方,一個(gè)是在左子樹患亿,一個(gè)在右子數(shù),一個(gè)經(jīng)過根節(jié)點(diǎn)
2 這種問題一般用遞歸來(lái)實(shí)現(xiàn)
3 根節(jié)點(diǎn)為root的二叉樹的直徑=max(左子樹直徑蜕猫,右子樹直徑箫措,左子樹最大深度(不包括根節(jié)點(diǎn))+右子樹最大深度(不包括根節(jié)點(diǎn))+1)
4 這里深度和路徑的概念是不一樣的
5 對(duì)于每一個(gè)節(jié)點(diǎn)腹备,通過這個(gè)節(jié)點(diǎn)的直徑=左子樹的最大深度+右子樹的最大深度
6 深度是節(jié)點(diǎn)數(shù)
7 全局變量會(huì)追蹤最長(zhǎng)path
1 刷這么多遍還是出錯(cuò)!=锫植酥!
每次返回時(shí)count的edge是其上面的edge,因?yàn)楸热鏲ount葉子節(jié)點(diǎn)的edge弦牡,就是其上面的友驮。所以在寫上面的code時(shí),直接是left+right就行了