leetcode 104. 二叉树的最大深度 递归/层序遍历

博客提及树的两种遍历方式,一是递归遍历,强调‘见树用递归’;二是层序遍历,指出其耗时更短。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、“见树用递归”

int maxDepth(struct TreeNode* root){
    int left, right;
    if(0 == root) return 0;
    if(0 == root->left && 0 == root->right) return 1;
    
    left = maxDepth(root->left);
    right = maxDepth(root->right);
    
    return 1+(left>right?left:right);
}

时间太久了

二、层序遍历
|

class Solution {
	public:
		int maxDepth(TreeNode* root) {
			int cout =0;
			if(root == NULL) return cout;
			queue <TreeNode* > q;
			q.push(root);

			while(!q.empty()) {
				int nums = q.size();//用于记录该层有多少个元素

				while(nums >0 ) {
					TreeNode*  temp =  q.front();
					q.pop();
					if(temp->left != NULL)   q.push(temp ->left); //左孩子入队
					if(temp->right != NULL)  q.push(temp ->right); //右孩子入队
					nums--;
				}

				if(nums == 0)  cout++;   //遍历完该层
			}
			return cout;
		}
};

耗时更短

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值