CODE 22: Minimum Depth of Binary Tree

来源:互联网 发布:淘宝0元购在哪里 编辑:程序博客网 时间:2024/05/21 10:01

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 int minDepth(TreeNode root) {// Start typing your Java solution below// DO NOT write main() functionif (null == root) {return 0;}Queue<TreeNode> queue = new LinkedList<TreeNode>();queue.offer(root);int layer = 1;int layerNumbers = 1;while (!queue.isEmpty()) {TreeNode node = queue.poll();layerNumbers--;if (null == node.left && null == node.right) {break;}if (null != node.left) {queue.offer(node.left);}if (null != node.right) {queue.offer(node.right);}if (layerNumbers == 0 && !queue.isEmpty()) {layerNumbers = queue.size();layer++;}}return layer;}


 

 

原创粉丝点击