这题大体思路就是通过遍历或者递归来解决。
评论区大佬的递归:
/**
* 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) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
层次遍历的解法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int dep=0;
public int maxDepth(TreeNode root) {
//root为空
if(root==null)return 0;
//进行层序遍历(广度优先遍历)
bfs(root,0);
//返回结果
return dep;
}
/*
利用depMirror记录当前深度,当左右子树遍历完毕后和dep比较,取最大,则为解
*/
public void bfs(TreeNode root,int depMirror){
//深度副本加一
depMirror++;
//遍历左子树(如果不为空)
if(root.left!=null)bfs(root.left,depMirror);
//遍历右子树(如果不为空)
if(root.right!=null)bfs(root.right,depMirror);
//比较左右子树深度,取最大的
dep=Math.max(depMirror,dep);
}
}