这个最好的就是递归了:
maxDepth函数返回的就是当前这个节点的状态,没有叶子,深度就是一,有叶子,继续用这个函数查看叶子的状态;
/**
* 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;
}else if(root.left==null&&root.right==null){
return 1;
}else{
int leftDepth =maxDepth(root.left);
int rightDepth=maxDepth(root.right);
if(leftDepth>rightDepth){
return leftDepth+1;
}else{
return rightDepth+1;
}
}
}
}