1. 题目描述
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.
题意:给出一个二叉树,求该二叉树的最小深度(从叶节点到根结点的最小值)。
2. 解题思路
按照广度遍历的顺序,找到第一个叶子节点,该节点到根结点的距离即为该二叉树最小深度。
3. 代码实现
package com.tree.deepth;
import java.util.*;
/**
* @author zhulongkun20@163.com
* @since 2018/11/2 下午7:43
*/
public class Solution {
public int run1(TreeNode root) {
if (root == null)
return 0;
LinkedList<TreeNode> queue = new LinkedList<>();
int level = 1;
TreeNode last, now;
last = now = root;
queue.add(root);
while (queue.size() != 0) {
TreeNode node = queue.poll();
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
if (node.left == null && node.right == null)
return level;
if (node == last) {
level++;
last = queue.getLast();
}
}
return level;
}
}
网友评论