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

2023-03-07,,

求二叉树的最大深度

基本思路如下:

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

LeetCode 腾讯精选50题--二叉树的最大深度的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。