【Leetcode】104. 二叉树的最大深度(简单)
2023-09-11 14:15:38 时间
一、题目
1、题目描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
2、基础框架
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
}
};
3、原题链接
二、解题报告
1、思路分析
(1)找到左右子树中较高的深度,加上根节点的这一层
2、代码详解
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
//
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
相关文章
- Leetcode: Expression Add Operators
- Leetcode: Flip Game
- LeetCode Anagrams My solution
- 【Leetcode】101. 对称二叉树(简单)
- LeetCode 剑指offer 68【二叉树的最近公共祖先】
- [LeetCode]剑指 Offer 55 - I. 二叉树的深度
- [LeetCode]657. 机器人能否返回原点
- [LeetCode]461. 汉明距离
- 110、【树与二叉树】leetcode ——450. 删除二叉搜索树中的节点:递归法+迭代法(C++版本)
- 99、【树与二叉树】leetcode ——113. 路径总和 II:回溯法两种版本(C++版本)
- 【leetcode】111:二叉树的最小深度
- [LeetCode] Binary Trees With Factors 带因子的二叉树
- [LeetCode] Kth Largest Element in a Stream 数据流中的第K大的元素
- [LeetCode] 654. Maximum Binary Tree 最大二叉树
- [LeetCode] Maximum Length of Pair Chain 链对的最大长度
- [LeetCode] Construct String from Binary Tree 根据二叉树创建字符串
- [LeetCode] 536. Construct Binary Tree from String 从字符串创建二叉树
- [LeetCode] Repeated Substring Pattern 重复子字符串模式
- [LeetCode] Power of Three 判断3的次方数
- [LeetCode] 236. Lowest Common Ancestor of a Binary Tree 二叉树的最小共同父节点
- [LeetCode] 83. Remove Duplicates from Sorted List 移除有序链表中的重复项
- LeetCode合并二叉树
- leetcode 617. Merge Two Binary Trees 合并二叉树(简单)
- leetcode 637. Average of Levels in Binary Tree 二叉树的层平均值(简单)
- leetcode 114. Flatten Binary Tree to Linked List 二叉树展开为链表(简单)
- leetcode 257. Binary Tree Paths 二叉树的所有路径(简单)