数据结构与算法之树
来源:互联网 发布:网站域名授权系统源码 编辑:程序博客网 时间:2024/06/07 05:34
这是我在牛客网做的leetcode题
题目是
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
中文大意是:求解二叉树的最小深度
/**
* 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;
}
if(root.right == null){
return 1+run(root.left);
}
if(root.left == null){
return 1+run(root.right);
}
if(root.right !=null && root.left != null){
return 1+Math.min(run(root.right),run(root.left));
}
return -1;
}
}
接下来,做个延伸,求解二叉树的最大深度,还是一递归的方式求解(有时间可以试试深度优先搜索DFS思维)
public int runMax(TreeNode root){
return root== null ?0:Math.max(runMax(root.left), runMax(root.right));
}
- 数据结构与算法之----树
- 数据结构与算法之树
- 数据结构与算法之二叉树遍历
- 数据结构与算法之二叉树
- 白话算法与数据结构之【字典树】
- 算法与数据结构之二叉树
- 数据结构与算法之九 树结构
- 数据结构与算法之二叉树
- 数据结构与算法04 之二叉树
- 数据结构与算法之二叉树
- <数据结构与算法>之二叉查找树
- 数据结构与算法之八(二叉树)
- 数据结构与算法学习笔记之--数据结构
- 数据结构与算法之----图
- 数据结构与算法之----串
- 数据结构与算法之队列
- 算法与数据结构之单链表
- 数据结构与算法之数组
- Kali安装中文输入法
- RabbitMQ
- H3C 三层交换机策略路由配置方法
- 新路程------wifi配置成WiFi热点
- 搭建高可用mongodb集群 replica set—— 深入副本集内部机制
- 数据结构与算法之树
- 超方便的数组去重
- 目标文件--omf
- vim常用命令
- 欢迎使用CSDN-markdown编辑器
- Java初尝试者
- onselectstart="return false" : 禁止选取
- 关于Eclipse4.7安装TomcatPlugin后无法显示三只猫问题
- hexo yilia 添加友言畅言评论支持