求二叉树最大深度 自定向下求法 1.添加一个自变量保存最后的深度值answer 2.构造方法,参数是(root,最深深度depth) 3.判断root是否存在,不存在就返回 4.如果root没有左右孩子,就判断之前保存的深度值answer与该支链上的深度值depth哪个大,将更大的值赋值给answer 5.如果root有左右孩子,就递归下一个结点 6.一直到root不存在,返回answer private int answer; // don't forget to initialize answer before call maximum_depth private void maximum_depth(TreeNode root, int depth) { if (root == null) { return; } if (root.left == null && root.right == null) { answer = Math.max(answer, depth); } maximum_depth(root.left, depth + 1); maximum_depth(root.right, depth + 1); } 自底向上求法 1.构造方法,参数(root) 2.判断root是否为null,是就return 0 3.递归,调用左右孩子的方法 4.比较左右孩子的深度并+1,返回该值 public int maximum_depth(TreeNode root) { if (root == null) { return 0; // return 0 for null node } int left_depth = maximum_depth(root.left); int right_depth = maximum_depth(root.right); return Math.max(left_depth, right_depth) + 1; // return depth of the subtree rooted at root } 部分内容转载自leedcode