Minimum Depth of Binary Tree
来源:互联网 发布:网络歌手伤感歌曲大全 编辑:程序博客网 时间:2024/05/18 03:54
Q:
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.
Solution:
/** * Definition for binary tree * 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 depth(root); } int depth(TreeNode node) { if (node == null) return Integer.MAX_VALUE; if (node.left == null && node.right == null) return 1; return Math.min(depth(node.left), depth(node.right)) + 1; }}
Level order traversal should be faster since it does not need to visit all the nodes.
/** * Definition for binary tree * 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; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); boolean found = false; int level = 0; while (!queue.isEmpty()) { if (found) break; level++; Queue<TreeNode> levelQueue = new LinkedList<TreeNode>(); while (!queue.isEmpty()) { TreeNode node = queue.poll(); if (node.left == null && node.right == null) found = true; if (node.left != null) levelQueue.offer(node.left); if (node.right != null) levelQueue.offer(node.right); } queue = new LinkedList<TreeNode>(levelQueue); } return level; }}
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
- java正则解析读取csv文件
- HDU1003 Max Sum
- 浅谈HTTP routing
- Linux 编译的四个阶段
- 通往阿里之路
- Minimum Depth of Binary Tree
- android数据库
- WM_NOTIFY消息
- wget: unable to resolve host address的解决方法
- java设计模式示例
- Android开发小问题集
- JS 常用函数 去空格、去重复元素 jquery去空格 1410231
- ubuntu安装ftp服务器
- Azure网站上的PHP — 架构