如何求二叉树的高度(递归实现)

核心代码

比较左右子树的高度,把高的那个子树+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");

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值