题目及测试
package sword039;
/*题目:输入一棵二叉树的根节点,求该数的深度。从根节点到叶结点依次进过的结点(含根,叶结点)形成树的一条路径,最长路径的长度为树的深度。
*/
public class main {
public static void main(String[] args) {
Object[] x=new Object[]{3,9,20,null,null,15,7};
BinaryTree tree=new BinaryTree(x);
BinaryTree.printTree(tree.root);
test(tree.root);
}
private static void test(TreeNode ito) {
Solution solution = new Solution();
int rtn;
long begin = System.currentTimeMillis();
rtn = solution.maxDepth(ito);//执行程序
long end = System.currentTimeMillis();
System.out.println("rtn=" );
System.out.print(rtn);
System.out.println();
System.out.println("耗时:" + (end - begin) + "ms");
System.out.println("-------------------");
}
}
解法1(成功)
如果一棵树只有一个结点,它的深度为1,如果根节点只有左子树而没有右子树,那么树的深度应该是其左子树的深度+1.同样如果根节点只有右子树而没有左子树,那么树的深度应该是其右子树+1.如果既有左子树又有右子树,那概述的深度就是左、右子树的深度的较大值加1.。
利用这个思路,我们可以用递归来实现代码:
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}