【力扣LeetCode】104 二叉树的最大深度

题目描述(难度易)

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],
在这里插入图片描述
返回它的最大深度 3 。

链接

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

思路

1、通过递归的方式,按深度优先的方式依次访问每一层,记录下以当前节点为根节点的最大深度值。
2、通过1的方式,递归会导致记录数最终少1,因为记录的是,3–9,20–7这样的边的个数。修正一下即可。

代码

class Solution {
public:
	int maxDepth(TreeNode* root) {
		if(root == NULL){
			return 0;
		}
		return getDepth(root) + 1;
	}
    int getDepth(TreeNode* root) {
    	int depth = 0;
    	int leftdepth = 0;
    	int rightdepth = 0;
		if(root == NULL){
			return depth;
		}
		else{
			if(root->left){
				leftdepth = getDepth(root->left) + 1;
			}
			if(root->right){
				rightdepth = getDepth(root->right) + 1;
			}
		}
		depth = leftdepth < rightdepth ? rightdepth : leftdepth;
		return depth;
    }
};

另一种写法:

class Solution {
public:
	int maxDepth(TreeNode* root) {
		int depth = 0;
    	int leftdepth = 1;
    	int rightdepth = 1;
		if(root == NULL){
			return depth;
		}
		else{
			if(root->left){
				leftdepth = maxDepth(root->left) + 1;
			}
			if(root->right){
				rightdepth = maxDepth(root->right) + 1;
			}
		}
		depth = leftdepth < rightdepth ? rightdepth : leftdepth;
		return depth;
	}
};
发布了164 篇原创文章 · 获赞 26 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/u013095333/article/details/98051039
今日推荐