【题目描述】
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.
Subscribe to see which companies asked this question
【思路】题目很简单,但考的很基础。二叉树的遍历方式有两种:递归和非递归,本题也有两种解法。
【解法1——递归实现】
/**
* 递归实现
* @param root
* @return
*/
public static int maxDepth(TreeNode root){
int depth = 0;
if (root != null) {
int leftDepth = maxDepth(root.left);
int rithtDepth = maxDepth(root.right);
depth ++ ;
if (leftDepth < rithtDepth) {
depth += rithtDepth;
}else {
depth += leftDepth;
}
}
return depth;
}