首页 > 其他 > 详细

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

时间:2019-08-12 21:10:48      阅读:117      评论:0      收藏:0      [点我收藏+]

求二叉树的最大深度,

基本思路如下:

设定一个全局变量记录二叉树的深度,利用递归,没遍历一层都将临时深度变量+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 }

 

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

原文:https://www.cnblogs.com/Kaithy-Rookie/p/11342147.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!