码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-Minimum Depth of Binary Tree

时间:2016-05-10 07:06:18      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

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.
/**
 * 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) {
        ArrayList<TreeNode> prev = new ArrayList<TreeNode>();
        
        if(root!=null) prev.add(root);
        int depth=0;
        while(!prev.isEmpty()){
            ArrayList<TreeNode> temp = new ArrayList<TreeNode> ();
            for(TreeNode node:prev){
                if(node.left!=null) temp.add(node.left);
                if(node.right!=null) temp.add(node.right);
                if(node.left==null && node.right ==null){
                    depth++;
                    return depth;
                }
            }    
            prev = new ArrayList<TreeNode>(temp);
            depth++;
        }
        return depth;
    }
}

  

LeetCode-Minimum Depth of Binary Tree

标签:

原文地址:http://www.cnblogs.com/incrediblechangshuo/p/5476413.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!