美文网首页
111 Minimum Depth of Binary Tree

111 Minimum Depth of Binary Tree

作者: yangminz | 来源:发表于2018-07-27 21:31 被阅读6次

title: Minimum Depth of Binary Tree
tags:
- minimum-depth-of-binary-tree
- No.111
- simple
- tree
- breadth-first-search


Description

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

Corner Cases

  • empty root

Solutions

Layer-First Traverse

Apply BFS, return when there is a leaf node.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int minDepth(TreeNode root) {
        Queue<TreeNode> que  = new LinkedList<TreeNode>();
        
        if (root == null) {return 0;}
        que.offer(root);
        int curr = 0;
        int nlay = 1;
        int dept = 1;

        while (!que.isEmpty()) {
            nlay = que.size();
            curr = 0;
            while(curr < nlay) {
                TreeNode x = que.poll();
                if (x.left == null && x.right == null) {return dept;}
                if (x.left  != null)                   {que.offer(x.left);}
                if (x.right != null)                   {que.offer(x.right);}
                curr = curr + 1;
            }
            dept = dept + 1;
        }
        return dept;
    }
}

相关文章

网友评论

      本文标题:111 Minimum Depth of Binary Tree

      本文链接:https://www.haomeiwen.com/subject/awfnmftx.html