24/01/31总结

本文介绍了一种使用C++编程语言实现的动态二叉树深度计算方法,通过递归函数dfs进行节点插入,并利用dfs2函数求解树的最大深度。
摘要由CSDN通过智能技术生成

P4913 【深基16.例3】二叉树深度

思路:动态建立二叉树,然后从头结点深度遍历,找到最大的深度
ac:

#include "iostream"
using std::cin;
using std::cout;
using std::endl;
int n,a,b,temp=1;
int max=0;
struct Tree{
	int data;
	struct Tree* lchild;
	struct Tree* rchild;
};

void dfs(int x, Tree* T) {
	if (T == NULL)
		return;
	if (T->data == x)
	{
		if (a != 0) {
			Tree* q = new Tree;
			q->data = a;
			T->lchild = q;
			q->lchild = NULL;
			q->rchild = NULL;
		}
		else T->lchild = NULL;
		if (b != 0) {
			Tree* p = new Tree;
			p->data = b;
			T->rchild = p;
			p->lchild = NULL;
			p->rchild = NULL;
		}
		else T->rchild = NULL;
		return;
	}
	dfs(x, T->lchild);
	dfs(x, T->rchild);
}

void dfs2(Tree* T, int temp) {
	if (T == NULL) {
		if (temp - 1 > max)
		{
			max = temp - 1;
		}
		return;
		if (temp - 1 > max) {
			max = temp - 1;
		}
	}
	dfs2(T->lchild, temp + 1);
	dfs2(T->rchild, temp + 1);
	
}
int main() {
	cin >> n;
	Tree* root = new Tree;
	root->data = 1;
	cin >> a >> b;
	if (a != 0) {
		Tree* q = new Tree;
		q->data = a;
		root->lchild = q;
		q->lchild = NULL;
		q->rchild = NULL;
	}
	else root->lchild = NULL;
	if (b != 0) {
		Tree* p = new Tree;
		p->data = b;
		root->rchild = p;
		p->lchild = NULL;
		p->rchild = NULL;
	}
	else root->rchild = NULL;
	for (int i = 1; i < n; i++) {
		cin >> a >> b;
		dfs(i + 1, root);
	}
	dfs2(root,temp);
	cout << max;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值