二叉樹進階之求一棵二叉樹中結點間最大距離:轉載自:http://www.cnblogs.com/ygj0930/p/6618074.html
二叉樹中的結點間距離:從結點A出發到達B,每個結點只能走一次,AB路徑上的結點數就是AB間距離。
由於從一個結點出發時,只有兩種方向可走:向上經過父節點到達它的兄弟子樹;向下到達它自己的左右子樹;
對於一個結點h爲根的子樹:假設現在從h左子樹中最深的葉結點逐層向上走,一直走到h的左兒子,現在h.left有兩種選擇:
一是向上經過h,然後到達h的右子樹向下走到最深葉結點;
二是從h.left的右兒子往下走,一直走到h.left的右子樹的最深葉結點;
兩種走法得到的路徑長度的最大值,就是以h爲根的子樹的結點間距離最大值。
情況1:h.left的右子樹比 h+h的右子樹 更深
此時:以h爲根的樹的結點間最大距離在h的左子樹中;
情況2:h+h的右子樹 比h.left的右子樹更深:
此時:h爲根的樹的結點間最大距離就是跨過h,從h的左子樹最深處到h右子樹最深的的路徑距離。
從右邊最深結點開始向上走的情況也一樣:h+h.right的左子樹 比 h的左子樹 更深時,h樹的結點間最大距離在h的右子樹中;否則,就是經過h的,從右最深到達左最深的路徑距離。
那麼由以上情況我們就可以分析出:以h爲根的二叉樹的結點間最大距離的可能情況:
1:爲左子樹的結點間最大距離;
2:爲右子樹的結點間最大距離;
3:爲經過h的左子樹最深葉結點到右子樹最深葉結點的路徑長,亦即:h的左子樹最大深度+h的右子樹最大深度+1。
採用後序遍歷的方式:對當前結點h,先獲取左子樹結點間最大距離以及左子樹最大深度,再獲取右子樹結點間最大距離以及右子樹深度,最後統計出h的結點間最大距離以及h的最大深度並返回上層。遞歸獲取兩個值:一個是子樹的最大深度,一個是子樹的結點間最大距離。其中,子樹最大深度通過一個數組傳引用的方式獲取結果;子樹的最大結點間距離則由遞歸函數的返回值返回.
public int findLongest(TreeNode root) { int[] depth=new int[1]; int max_distance=getMaxDistance(root,depth); return max_distance; } //遞歸獲取兩個值:一個是子樹的最大深度,一個是子樹的結點間最大距離。 //其中,子樹最大深度通過一個數組傳引用的方式獲取結果;子樹的最大結點間距離則由遞歸函數的返回值返回 public int getMaxDistance(TreeNode curr,int[] depth){ //結點爲空,則高度爲0,結點最大距離爲0 if(curr==null){ depth[0]=0; return 0; } //遞歸左子樹獲取左子樹最大結點距離 int left_child_max_distance=getMaxDistance(curr.left,depth); //通過數組獲取左子樹遞歸過程中統計出的子樹深度 int left_child_depth=depth[0]; //遞歸右子樹獲取右子樹最大結點距離 int right_child_max_distance=getMaxDistance(curr.right,depth); //通過數組獲取右子樹遞歸過程中統計出的子樹深度 int right_child_depth=depth[0]; //通過數組記錄當前結點的高度 depth[0]=Math.max(left_child_depth+1,right_child_depth+1); //比較 左子樹最大結點距離、右子樹最大結點距離、經過當前結點到達左右子樹最深結點的路徑距離,最大者就是當前結點爲根的樹的最大結點距離 return Math.max(Math.max(left_child_max_distance,right_child_max_distance),left_child_depth+right_child_depth+1); }
PHP代碼實現
<?php
class Node{
public $data;
public $left;
public $right;
}
function getMaxDistance($root,&$depth){
if($root==null){
$depth=0;
return 0;
}
$left_max_distance=getMaxDistance($root->left,$depth);
$left_depth=$depth;
$right_max_distance=getMaxDistance($root->right,$depth);
$right_depth=$depth;
$depth=max($left_depth+1,$right_depth+1);
return max(max($left_max_distance,$right_max_distance),$left_depth+$right_depth+1);
}
function test(){
$tree=new Node();
$b=new Node();
$c=new Node();
$d=new Node();
$f=new Node();
$g =new Node();
$e=new Node();
$h=new Node();
$i=new Node();
$j=new Node();
$k=new Node();
$l=new Node();
$m=new Node();
$tree->data='A';
$b->data='B';
$c->data='C';
$d->data='D';
$e->data='E';
$f->data='F';
$g->data='G';
$i->data='I';
$h->data='H';
$j->data='J';
$k->data='K';
$l->data='L';
$m->data='M';
$tree->left=$b;
$tree->right=$c;
$b->left=$d;
$b->right=$e;
// $c->left=$f;
//$c->right=$g;
$e->left=$h;
$h->left=$i;
$d->left=$j;
$j->left=$k;
$k->left=$l;
$i->left=$m;
$max_distance=getMaxDistance($tree,$depth=0);
echo $max_distance;
}
test();
?>