LeetCode 腾讯精选50题--二叉树的最大深度

求二叉树的最大深度,

基本思路如下:

设定一个全局变量记录二叉树的深度,利用递归,没遍历一层都将临时深度变量+1,并在每一节点递归结束后判断深度大小。

具体代码如下:

 1 package algorithm;
 2 
 3 
 4 import basic.TreeNode;
 5 
 6 public class MaxDepthOfTree {
 7 
 8     private int depth = 0;
 9     public int maxDepth(TreeNode root) {
10         acquireDepth(root,0);
11         return depth;
12     }
13 
14     private int acquireDepth(TreeNode root,int i){
15         if(root == null){
16             return i;
17         }
18         i++;
19         acquireDepth(root.left,i);
20         acquireDepth(root.right,i);
21         depth = Math.max(depth,i);
22         return i;
23     }
24    
25 }
原文地址:https://www.cnblogs.com/Kaithy-Rookie/p/11342147.html