题目:Maximum Depth of Binary Tree
描述:Given a Binary Tree, find its maximum depth
The maximum depth is the number of nodes along the longest path from the root node to the farthest leaf node.
Java code:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}else{
int res = 1;
int l = maxDepth(root.left);
int r = maxDepth(root.right);
return l > r? l + 1:r + 1;
}
}
}
①有输入的,先考虑输入!考虑输入:输入为null,深度为0
②只有根节点,深度为1;
③已有方法maxDepth(root.left)求最长路径,深度=最长路径+1