1. 程式人生 > >二叉樹求深度解析

二叉樹求深度解析

小白部落格
看下圖為示例
在這裡插入圖片描述
先貼出求深度程式碼
int Depth(Bitree root) {

int hl,hr,max;
if(root) {
    hl = Depth(root->left);
    hr = Depth(root->right);
    max = hl>hr?hl:hr;
    printf("%c:Depth->%d\n",root->data,max+1);
    return (max+1);
}
else return 0;

}
//先會一直執行h1 = Depth(root->left);(注意:root也在改變)
//直到D->left = NULL 返回0,這是最後一層hl = 0;
//繼續指行hr = Depth(root->right);(注意:還是最後一層,root=D)
//同理最後一層hr = 0,執行max = …返回1,(D單獨的深度為1)。
//返回上一層(回溯),回到B的一層,此時B層的hl = 1,(上一步返回的)
//執行hr = Depth(root->right)(root=B)進入下一層F
//遞迴呼叫,F->left不為空,繼續下一層E,E左右為空,同理上述D
//回溯,F層的hl = 1,hr = 0,呼叫max=…得到B層的hr=2
//然後呼叫第一層的A->right,同上步驟,最終得到深度為4在這裡插入圖片描述