[leetcode]maximum-depth-of-binary-tree C++

本文介绍了一种使用递归方法求解二叉树最大深度的问题,并对初始代码进行了优化,提高了执行效率。

题目:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

分析:

此题用递归的方式做非常简单,虽然一次性就通过了,但是之所以记下来,是因为还有一些细节自己处理的并不完善,说明了思考应该更加周到而且不冗余。


代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int max(int a, int b)
	{
		return a > b ? a : b;
	}
	int maxDepth(TreeNode *root) {
		if(root == NULL)return 0;
		else if ((root->left == NULL) && (root->right == NULL))return 1;
		else if (root->left == NULL)return 1+maxDepth(root->right);
		else if (root->right == NULL)return 1+maxDepth(root->left);
		else
		{
			return max(maxDepth(root->left), maxDepth(root->right)) + 1;
		}


	}
};
自我分析:

其实代码中那三个else if语句可以完全省略,因为当左子树或者右子树为空后,调用madDepth函数,本身在最开始的时候会判断是否为NULL,如果是,直接返回。以后思考的时候注意,不仅仅要全面,同时要做到不冗余。另外,从执行效率的角度上,不是很建议用上述判断左右子树谁的深度最大,因为函数的调用存在开销的,将左右字数的深度存放于一个temp值中,用temp值进行比较效率更高。

优化后的代码:

int maxDepth(TreeNode *root) {
    if(root == NULL)return 0;	
    int ltmp = maxDepth(root->left);
    int rtmp = maxDepth(root->right);
    return 1+(ltmp>rtmp?ltmp:rtmp);
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值