2020.7.28 力扣每日
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int maxDepth(TreeNode root) { 12 if (root == null) 13 return 0; 14 return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; 15 } 16 }
简单的递归DFS。
上面是精简版,下面这个便于理解些。
1 class Solution { 2 public int maxDepth(TreeNode root) { 3 return Depth(root, 0); 4 } 5 public int Depth(TreeNode root, int Depth){ 6 if (root == null) 7 return Depth; 8 return Math.max(Depth(root.left, Depth + 1), Depth(root.right, Depth + 1)); 9 } 10 }