题目:
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.
Note: A leaf is a node with no children.
解答:
这个题比较简单,运用递归的思想即可,二叉树的最大深度=Max(左子树的最大深度+1,右子树的最大深度+1)
结束条件:当遍历到叶子节点的左子树或叶子节点的右子树为null时,即root==null,直接return 0
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int left=maxDepth(root.left)+1;
int right=maxDepth(root.right)+1;
return left>right?left:right;
}
}