序
本文主要记录一下leetcode树之二叉树的深度
![abc31e9b5f1233eca7524d0ccbc6a5e0.png](https://img-blog.csdnimg.cn/img_convert/abc31e9b5f1233eca7524d0ccbc6a5e0.png)
题目
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。例如:给定二叉树 [3,9,20,null,null,15,7], 3 / 9 20 / 15 7返回它的最大深度 3 。提示: 节点总数 <= 10000注意:本题与主站 104 题相同:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public int maxDepth(TreeNode root) { if(root == null) { return 0; } int leftDepth = maxDepth(root.left) ; int rightDepth = maxDepth(root.right) ; return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; }}
小结
这里采用递归的方式,递归计算maxDepth(root.left)及maxDepth(root.right),最后取它们的最大值+1。
doc
- 二叉树的深度