剑指offer--二叉树的最大深度
二叉树的深度
http://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b
解法
通过递归的方式获取到左子树的长度 和右子树的长度 ,然后比较谁大 最后将结果 加上根节点的深度1
代码
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return left>right?left+1: right+1;
}
}
查看14道真题和解析