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.
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int minDepth(TreeNode root) { 12 if(null == root){//空树 13 return 0; 14 } 15 else if(null != root && null == root.left && null == root.right)//只有根节点的树 16 return 1; 17 else if(null != root && null != root.left && null == root.right){//只有左子树 18 return minDepth(root.left) + 1; 19 } 20 else if(null != root && null == root.left && null != root.right){//只有右子树 21 return minDepth(root.right) + 1; 22 }else{//左右子树都有 23 int min = minDepth(root.left); 24 if(min > minDepth(root.right)) 25 min = minDepth(root.right); 26 return min + 1; 27 } 28 } 29 }
这道题主要是求根节点到叶子节点最短路径的长度,这里我借鉴了求树的深度算法。用的是递归实现的
如果是空树直接返回0
如果只有根节点返回1
如果只有左子树返回左子树的最短路径长度+1
如果只有右子树返回右子树的最短路径长度+1
如果有左右子树返回左右子树中最短路劲长度 + 1,这里需要比较左右子树最短路径长度,取最小那个返回