Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
用递归,随便写了写就过了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public static int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return findDepth(root,0);
}
private static int findDepth(TreeNode node,int depth){
int result;
if(node==null){
result=depth;
return result;
}
result=max(findDepth(node.left,depth+1),findDepth(node.right,depth+1));
return result;
}
private static int max(int x,int y){
return x>y?x:y;
}
}