1. 程式人生 > >計算二叉樹的高度

計算二叉樹的高度

pri 最大值 二叉樹的高度 bubuko 依據 樹的高度 http 函數 str

沿每個節點v到根r的唯一通路上節點數目,稱作v 的深度(depth),記作depth(v)。

依據深度排序,可對所有節點做分層歸類。特別地,約定根節點的深度 depth(root) = 1,

故屬於第1層。

樹T中所有節點深度的最大值稱作該樹的高度(height),記作height(T)。空樹的高度為0。

下面這棵二叉樹的高度為3。

技術分享圖片

我們可以遞歸的計算出左子樹的高度和右子樹的高度,然後取二者的最大值加1最為這棵二叉樹的高度。

Algorithm:

  height(T)
1. 如果樹為空,則返回0
2. 否則
     (a) 通過遞歸地調用height(T.left)求出左子樹的高度
     (b) 通過遞歸的調用height(T.right)求出右子樹的高度
     (c) 利用如下公式求出二叉樹的高度:
        height(T) = max(height(T.left),  height(T.right)) + 1
     (d) 返回height(T)

下圖詮釋了遞歸求解過程:
            height(‘1‘) = max(height(‘2‘), height(‘3‘)) + 1
                               = 2 + 1
                                  /                                    /                                       /                                         /                                           /                                    height(‘2‘) = 1                height(‘3‘) = 1
= max(height(‘4‘), height(‘5‘)) + 1
= 1 + 1   = 2         
                   /                     /                       /                         /                           /                     height(‘4‘) = 1     height(‘5‘) = 1

#include<stdio.h> 
#include<stdlib.h> 
  
  
/*
* 二叉樹節點包含數據域,指向左子樹的指針,指向右子樹的指針
*/ struct node { int data; struct node* left; struct node* right; }; /*
* 計算二叉樹的高度
*/ int height(struct node* node)
{ if (node==NULL) return 0; else {
// 計算左子樹的高度和右子樹的高度 int lHeight = height(node->left);
int rHeight = height(node->right);
// 返回二者較大者加1 if (lHeight > rHeight) return(lHeight+1); else return(rHeight+1); } } /*
* 輔助函數
* 使用給定的數據生成二叉樹節點,節點的左子樹和右子樹均為空
*/ struct node* newNode(int data) { struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return(node); } int main() { struct node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("Height of tree is %d", height(root)); getchar(); return 0; }

計算二叉樹的高度