/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int maxdeep = 0;
public int maxDepth(TreeNode root) {
this.dfs(root,0);
return this.maxdeep;
}
public void dfs(TreeNode node,int deep){
if(node==null){
this.maxdeep = Math.max(this.maxdeep,deep);
return ;
}
this.dfs(node.left,deep+1);
this.dfs(node.right,deep+1);
}
}
解题思路:
这道题还是非常简单,最节点的左右子树进行递归并记录递归层数,直到节点为null,判断当前层数是否是新的最大层数即可。