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 binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int i=0;
public int run(TreeNode root) {
if(root == null){
return 0;
}
return getHeight(root);
}
public int getHeight(TreeNode root){
if(root.left == null && root.right == null){
return 1;
}
if(root.left == null){
return getHeight(root.right)+1;
}
if(root.right == null){
return getHeight(root.left)+1;
}
return Math.min(getHeight(root.left),getHeight(root.right))+1;
}
}