标签:
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