写在前面
难度:简单递归 + 高度更新
解题思想(化繁为简!!!)
问题转化巧妙树的深度为左子树的深度和右子树的深度的较大值+1.
题目详情
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
ac代码
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
int lh = maxDepth(root->left);
int rh = maxDepth(root->right);
return lh > rh ? lh+1: rh+1;
}
};
参考文章
剑指offer 面试题55 二叉树的深度
转载请注明原文地址:https://ipadbbs.8miu.com/read-14862.html