- 题目:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树[3,9,20,null,null,15,7]
,
1
2
3
4
5 3
/ \
9 20
/ \
15 7返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
时间复杂度上最小是$\Omega(N)=N$,也就是说至少每个节点遍历一遍。最简单的思路是DFS遍历一遍,过程中动态记录当前最大深度。拿中序遍历举例子,首先如果root不为空,那么深度+1,再遍历左子树,遍历完左子树返回,再遍历右子树,遍历完一个节点的左子树和右子树之后需要返回上一层,深度-1。
迭代代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
inorderTraversal(root);
return maxdepth;
}
private:
int curDepth;
int maxdepth;
void inorderTraversal(TreeNode* root){
if(!root) return;
++curDepth;
maxdepth = max(maxdepth, curDepth);
inorderTraversal(root->left);
inorderTraversal(root->right);
--curDepth;
}
};看了别人的递归:应该首先思考是否可以递归这个函数本身实现功能。
- 函数功能:求二叉树最大深度,可以拆分成求左右子树最大深度最大值+1
- 结束条件:节点为空,直接返回0
- 递推公式如上
极简递归代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};迭代就是用栈实现,略过,加速!