Minimum Depth of Binary Tree
来源:互联网 发布:java web编程实战宝典 编辑:程序博客网 时间:2024/04/30 20:44
题目地址:https://leetcode.com/problems/minimum-depth-of-binary-tree/
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.
这个题目正好与求树高的方法相反,求根节点到叶子节点最短路径的长度,依然用递归实现,注意左右子树只有存在其一时候的情况的处理:
public class MinimumDepthOfBinaryTree { public static int minDepth(TreeNode root) { if (root == null) return 0; else if (root.left == null && root.right == null) return 1; else if (root.left != null && root.right == null) return minDepth(root.left) + 1; else if (root.left == null && root.right != null) return minDepth(root.right) + 1; else return Math.min(minDepth(root.left) + 1, minDepth(root.right) + 1); } public static void main(String[] args) { TreeNode node1 = new TreeNode(5); TreeNode node2 = new TreeNode(4); TreeNode node3 = new TreeNode(8); TreeNode node4 = new TreeNode(11); TreeNode node5 = new TreeNode(13); TreeNode node6 = new TreeNode(4); TreeNode node7 = new TreeNode(7); TreeNode node8 = new TreeNode(2); TreeNode node9 = new TreeNode(1); node1.left = node2; node1.right =node3; node2.left = node4; node3.left = node5; node3.right = node6; node4.left = node7; node4.right = node8; node6.right = node9; System.out.println(minDepth(node1)); }}
0 0
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Minimum Depth of Binary Tree
- 【计算机视觉】Selective Search for Object Recognition论文阅读1
- souvenirs without help
- 基于Token的WEB后台认证机制
- linux下GraphicsMagick 的安装
- 通过appearance设置app主题
- Minimum Depth of Binary Tree
- 搭建自己的私有云
- PHP篇之爬取豆瓣电影Top250的电影名
- jsp 中ajax请求路径怎么写
- redis 存储数据结构及持久化方式--rdb 、aof
- 网易视频云朱玲:互动直播场景下的视频核心技术实践
- Leetcode 53. Maximum Subarray
- 【计算机视觉】Selective Search for Object Recognition论文阅读2
- 发送有序广播