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 }

 

posted @ 2019-08-12 19:45  奶昔书斋  阅读(304)  评论(0)    收藏  举报