求二叉树的最大深度,
基本思路如下:
设定一个全局变量记录二叉树的深度,利用递归,没遍历一层都将临时深度变量+1,并在每一节点递归结束后判断深度大小。
具体代码如下:
package algorithm; import basic.TreeNode; public class MaxDepthOfTree { private int depth = 0;
public int maxDepth(TreeNode root) {
acquireDepth(root,0);
return depth;
} private int acquireDepth(TreeNode root,int i){
if(root == null){
return i;
}
i++;
acquireDepth(root.left,i);
acquireDepth(root.right,i);
depth = Math.max(depth,i);
return i;
} }