递归解决
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0;
public int maxDepth(TreeNode root) {
if(root==null)
return 0;
depth(root,1);
return res;
}
public void depth(TreeNode root, int i) {
if (root.left != null) {
depth(root.left,i+1);
}
if (root.right!= null) {
depth(root.right,i+1);
}
this.res = Math.max(i, res);
}
}
别的解法太精炼了
/**
* 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;
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
}