给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶节点的最短路径的节点数量。详见:https://leetcode.com/problems/minimum-depth-of-binary-tree/description/Java实现:
递归实现:
/** * 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) { if(root==null){ return 0; } int minLeft=minDepth(root.left); int minRight=minDepth(root.right); if(minLeft==0||minRight==0){ return minLeft>=minRight?minLeft+1:minRight+1; } return Math.min(minLeft,minRight)+1; }}
非递归实现:
/** * 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) { if(root==null){ return 0; } LinkedListque=new LinkedList (); que.offer(root); int node=1; int level=1; while(!que.isEmpty()){ root=que.poll(); --node; if(root.left==null&&root.right==null){ return level; } if(root.left!=null){ que.offer(root.left); } if(root.right!=null){ que.offer(root.right); } if(node==0){ node=que.size(); ++level; } } return level; }}