求二叉树的深度是在面试过程中经常会出现的一道经典题目,关于树的题目很多都可以采用递归来求解,这是由树本身的结构决定的;这道题目也可以通过递归来求解。
思路:递归思想,一颗二叉树的深度为其左子树和右子树中的大者加1
代码:
<span style="font-size:12px;">public class Problem39 {
int depth(TreeNode root){
if(root == null)
return 0;
int leftDepth = depth(root.left);
int rightDepth = depth(root.right);
return leftDepth > rightDepth ? (leftDepth+1) : (rightDepth+1);
}
}</span>
剑指Offer第39题: http://ac.jobdu.com/problem.php?pid=1350