分析
难度 易
来源
https://leetcode.com/problems/minimum-depth-of-binary-tree
题目
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.
解答
1 package LeetCode; 2 3 import java.util.LinkedList; 4 import java.util.Queue; 5 6 public class L111_MinimumDepthOfBinaryTree { 7 public TreeNode makeBinaryTreeByArray(Integer[] array,int index){ 8 if(index<array.length&&array[index]!=null){ 9 int value=array[index]; 10 TreeNode t=new TreeNode(value); 11 array[index]=0; 12 t.left=makeBinaryTreeByArray(array,index*2+1); 13 t.right=makeBinaryTreeByArray(array,index*2+2); 14 return t; 15 }else 16 return null; 17 } 18 public int minDepth(TreeNode root) { 19 if(root==null) 20 return 0; 21 int left=minDepth(root.left); 22 int right=minDepth(root.right); 23 if(left==0||right==0) 24 //一个子树高度为零,当前节点非叶子节点,高度为非空子树的高度+1; 25 // 两个子树高度都为0,当前节点为叶子节点,高度为1 26 return Math.max(left,right)+1; 27 else 28 return Math.min(left,right)+1; 29 } 30 public void levelOrderTraversal(TreeNode root){//广度优先搜索+分层.注意非全二叉树插入空节点 31 if(root==null) 32 return; 33 Queue<TreeNode> queue=new LinkedList<TreeNode>(); 34 queue.offer(root); 35 int curCount=1;//记录当前层节点数 36 int nextCount=0;//记录下一层节点数 37 int outCount=0;//记录出队列节点数 38 while(!queue.isEmpty()){ 39 TreeNode node=queue.poll(); 40 outCount++; 41 if(node!=null){ 42 System.out.print(node.val);//空节点无值打印,直接输出下方的tab 43 queue.offer(node.left); 44 nextCount++; 45 queue.offer(node.right); 46 nextCount++; 47 } 48 System.out.print(" "); 49 if(outCount==curCount)//当前层全部出队列 50 { 51 System.out.println(); 52 curCount=nextCount; 53 nextCount=0; 54 outCount=0; 55 } 56 } 57 } 58 public static void main(String[] args){ 59 L111_MinimumDepthOfBinaryTree l111=new L111_MinimumDepthOfBinaryTree(); 60 Integer[] nums={3,9,20,null,null,15,7}; 61 //Integer[] nums={1,2,2,3,3,null,null,4,4}; 62 TreeNode root=l111.makeBinaryTreeByArray(nums,0); 63 l111.levelOrderTraversal(root); 64 System.out.println(l111.minDepth(root)); 65 } 66 }