Minimum Depth of Binary Tree
来源:互联网 发布:javascript 是什么 编辑:程序博客网 时间:2024/05/22 17:44
Recursive
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int minDepth(TreeNode root) { if (root == null) { return 0; } return getMin(root); } private int getMin(TreeNode node) { if (node == null) { return Integer.MAX_VALUE; } if (node.left == null && node.right == null) { return 1; } return Math.min(getMin(node.left), getMin(node.right)) + 1; }}
Iterative
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public int minDepth(TreeNode root) { int height = 0; if (root == null) { return height; } height++; Queue<TreeNode> currentLevel = new LinkedList<TreeNode>(); Queue<TreeNode> nextLevel = new LinkedList<TreeNode>(); Queue<TreeNode> temp; currentLevel.offer(root); while (true) { while (!currentLevel.isEmpty()) { TreeNode node = currentLevel.poll(); if (node.left == null && node.right == null) { return height; } if (node.left != null) { nextLevel.offer(node.left); } if (node.right != null) { nextLevel.offer(node.right); } } height++; temp = currentLevel; currentLevel = nextLevel; nextLevel = temp; } }}
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
- 如是中庸实例:SQL语句 将所有推荐人手机号改成对应手机号人的ID
- 携程App的网络性能优化实践
- HDU 2648(搜索题,哈希表)
- 扁平化设计与质感设计
- 欢迎使用CSDN-markdown编辑器
- Minimum Depth of Binary Tree
- 深度学习-LeCun、Bengio和Hinton的联合综述
- 开发iOS SDK注意事项
- 黑马程序员——字符流
- 南阳
- Spring学习笔记(二):Spring在STS中的配置和入门例子
- UML基础: 统一建模语言简介
- 自定义微博小尾巴(源码+解析)
- GRE北美范文:统一课程与多样化课程比较