二叉树的最大深度【c++】

本文介绍了如何使用C++编写一个函数`maxDepth`来计算给定双链表表示的二叉树的最大深度,通过递归方法实现,示例代码展示了从根节点1开始的树结构和计算得到的深度3。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <vector>
using namespace std;

//双链表节点结构
typedef struct treeNode {
	int value;
	struct treeNode* left;
	struct treeNode* right;
	treeNode(int x) : value(x), left(nullptr), right(nullptr) {}
} Node;

int maxDepth(Node* root)
{
	if(root == nullptr)
	{
		return 0;
	}
	else
	{
		int leftdepth = maxDepth(root->left);
		int rightdepth = maxDepth(root->right);
		return (leftdepth > rightdepth ? leftdepth : rightdepth) + 1;
	}
	
}

int main()
{
	Node* root = new Node(1);
	root->left = new Node(2);
	root->right = new Node(3);
	root->left->left = new Node(4);
	root->left->right = new Node(5);
	//         1
	//      2     3
	//   4    5
	cout << "depth : " << maxDepth(root) << endl;
	
	system("pause");
	return 0;
}
//         1
//      2     3
//   4    5
这个深度是3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值