题解 | #二叉树的最大深度#
二叉树的最大深度
http://www.nowcoder.com/practice/8a2b2bf6c19b4f23a9bdb9b233eefa73
解题思路 1
- 递归树节点的左右子节点
- 当节点为叶子节点,那么返回 1
- 因为是递归,因此可以为每次递归设置 +1 操作
- 比较每次递归左右节点的深度,将深度大的返回
代码实现
像二叉树、链表都可以使用递归的方式进行解决,可以说是比较简单的处理方式
public class Solution {
public int maxDepth (TreeNode root) {
// write code here
if(root == null)return 0;
// 叶子节点 返回 1 说明后面已经没有节点
if(root.left==null&&root.right==null)return 1;
int l_depth=0;
int r_depth=0;
while(true){
// 左右节点递归
l_depth = maxDepth(root.left) + 1;
r_depth = maxDepth(root.right) + 1;
// 返回左右节点中最大的深度
return l_depth>r_depth?l_depth:r_depth;
}
}
}
// 运行时间:66ms 超过26.98% 用Java提交的代码
// 占用内存:12228KB 超过45.46%用Java提交的代码
时间复杂度: 空间复杂度: