最大深度:从根节点到叶子节点的最长路径上的节点个数

最大深度为3
规则:
(1)二叉树为空,返回0
(2)递归计算左孩子和右孩子的深度,取最大值+1
代码实现
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int run(TreeNode root) {
if(root == null) return 0;
return Math.max(run(root.left),run(root.right))+1;
}
}
**最小深度:**从根节点到叶子节点的最短路径所经过的节点个数

最小深度为2
规则:
(1)二叉树为空,返回0
(2)如果二叉树没有右(左)孩子,则二叉树最小深度 = 左(右)孩子深度+1
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int run(TreeNode root) {
if(root == null) return 0;
else if(root.left == null) return run(root.right)+1;
else if(root.right == null) return run(root.left)+1;
return Math.min(run(root.left),run(root.right))+1;
}
}
本文探讨了如何求解二叉树的最大深度和最小深度。最大深度是从根节点到最远叶子节点的最长路径上的节点数量,而最小深度是从根节点到最近叶子节点的最短路径上的节点数量。对于最大深度,当二叉树为空时返回0,否则递归计算左右子树深度并取最大值加1。对于最小深度,空树返回0,若二叉树无右子树则最小深度等于左子树深度加1,反之亦然。
3397

被折叠的 条评论
为什么被折叠?



