马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
二叉树的深度是指从根节点到叶子节点的最长路径上的节点数。
一、最大深度
104. 二叉树的最大深度 - 力扣(LeetCode)
最大深度是指从根节点到最远叶子节点的最长路径上的节点数。
- //递归法
- /**
- * 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 {
- public int maxDepth(TreeNode root) {
- return getdepth(root);
- }
- public int getdepth(TreeNode root){
- if(root==null)return 0;
- int rdepth=getdepth(root.right);
- int ldepth=getdepth(root.left);
- int depth=Math.max(rdepth,ldepth)+1;
- return depth;
- }
- }
复制代码 二、最小深度
111. 二叉树的最小深度 - 力扣(LeetCode)
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
- //递归法
- /**
- * 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 {
- public int minDepth(TreeNode root) {
- return getdepth(root);
- }
- public int getdepth(TreeNode root){
- if(root==null)return 0;
- int rdepth=getdepth(root.right);
- int ldepth=getdepth(root.left);
- if(root.left==null&&root.right!=null)return rdepth+1;//左为空,右不为空,说明此时不是最近叶子结点
- if(root.left!=null&&root.right==null)return ldepth+1;//左不为空,右为空,说明此时不是最近叶子结点
- int depth=Math.min(rdepth,ldepth)+1;
- return depth;
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |