欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > 二叉树的最大深度(遍历思想+分解思想)

二叉树的最大深度(遍历思想+分解思想)

2025/2/6 14:07:35 来源:https://blog.csdn.net/LNsupermali/article/details/145389544  浏览:    关键词:二叉树的最大深度(遍历思想+分解思想)

Problem: 104. 二叉树的最大深度

文章目录

  • 题目描述
  • 思路
  • 复杂度
  • Code

题目描述

在这里插入图片描述在这里插入图片描述

思路

遍历思想(实则二叉树的先序遍历)

1.欲望求出最大的深度,先可以记录一个变量res,同时记录每次当前节点所在的层数depth
2.在递的过程中,每次递一层,也即使当前又往下走了一层,则depth++,当到达叶子节点时,比较并取出max【res, depth】
3.在归的过程中,因为是在往上层归,则depth–;
4.返回最终的res即可

分解思想

1.要求整个树的最大深度则可以分解其为求去当前节点的左右子树的最大深度再加当前节点的高度1

复杂度

二者均为
时间复杂度:

O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数

空间复杂度:

O ( h ) O(h) O(h);最坏空间复杂度

Code

遍历思想

/**
/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {// recode the maximum depth int res = 0;// recode the depth of the traversed nodeint depth = 0;public int maxDepth(TreeNode root) {traverse(root);return res;}public void traverse(TreeNode root) {if (root == null) {return;}depth++;if (root.left == null && root.right == null) {res = Math.max(res, depth);}traverse(root.left);traverse(root.right);depth--;}
}

分解思想

 class Solution {// Definition: Given the root node, return the maximum depth of the binary treepublic int maxDepth(TreeNode root) {if (root == null) {return 0;}// calculate the maximum depth of the left and right subtreesint leftMax = maxDepth(root.left);int rightMax = maxDepth(root.right);// The maximum depth of the entire tree is// the maximum of the left and right subtree// plus one for the root node itselfint res = Math.max(leftMax, rightMax) + 1;return res;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com