如何求二叉樹的高度(遞歸實現)

核心代碼

比較左右子樹的高度,把高的那個子樹+1返回,就是整棵樹的高度


int Height(BiTreeNode *head)
{
	if(head==NULL) return 0;
	else
	{
		int m=Height(head->LeftChild);
		int n=Height(head->RightChild);
		return (m>n)? (m+1):(n+1);
	}
}


完整代碼:

#include<iostream>
#include<assert.h>
using namespace std;
 

typedef struct Lnode
{
	char data;
	struct Lnode *LeftChild;
	struct Lnode *RightChild;
}BiTreeNode;

void Initiate(BiTreeNode **head)
{
	(*head)=(BiTreeNode *)malloc(sizeof(BiTreeNode));
	assert((*head)!=NULL); //if the judging conditio is true,this statement is not executed
	(*head)->LeftChild=NULL;
	(*head)->RightChild=NULL;
}

BiTreeNode * InsertLeftChild(BiTreeNode *head,char a )
{
	if(head==NULL) return NULL;
	BiTreeNode * p,*t;
	t=head->LeftChild;
	p=(BiTreeNode *)malloc(sizeof(BiTreeNode));
	assert(p!=NULL);
	p->data=a;
	p->RightChild=NULL;
	p->LeftChild=t;
	head->LeftChild=p;
	return head->LeftChild;
}

BiTreeNode *InsertRightChild(BiTreeNode *head,char a)
{
	if(head==NULL)  return NULL;
	BiTreeNode *p,*t;
	t=head->RightChild;
	p=(BiTreeNode *)malloc(sizeof(BiTreeNode));
	assert(p!=NULL);
	p->data=a;
	p->LeftChild=NULL;
	p->RightChild=t;
	head->RightChild=p;
	return head->RightChild;
}

void Destroy(BiTreeNode *head)
{
	if(head!=NULL && head->LeftChild!=NULL)
		Destroy(head->LeftChild);
	if(head!=NULL && head->RightChild!=NULL)
		Destroy(head->RightChild);
	free(head);
}

void LDR(BiTreeNode *head)
{
	if(head!=NULL)
	{
		LDR(head->LeftChild);
		cout<<head->data<<"  ";
		LDR(head->RightChild);
	}
}



int Height(BiTreeNode *head)
{
	if(head==NULL) return 0;
	else
	{
		int m=Height(head->LeftChild);
		int n=Height(head->RightChild);
		return (m>n)? (m+1):(n+1);
	}
}

void main()
{
	BiTreeNode *head,*p,*q;
	Initiate(&head);
	head->data='g';
	p=InsertLeftChild(head,'a');
	p=InsertLeftChild(p,'b');
	p=InsertRightChild(head,'c');

	LDR(head);
	cout<<endl;
	
	cout<<"the height:"<<Height(head)<<endl;
	Destroy(head);
	system("pause");

}

發佈了35 篇原創文章 · 獲贊 42 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章