题目描述
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: 当前节点为空: 返回0
情况2 :当前节点不为空:这边又分为两种情况: hl 表示左子树的最小深度, hr表示右子树的最小深度
1.左子树或右子树中一个是空 :那么左子树和右子树中最多一个是正数,因此高度当前节点高度是 hl + hr + 1;
2.左子树和右子树都非空: 那么当前节点高度是 min (hl + 1, hr + 1);
代码
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int run(TreeNode root) {
if (root == null) {
return 0;
}
int hl = run(root.left);
int hr = run(root.right);
if (hl == 0 || hr == 0) {
return hl + hr + 1;
}
return hl < hr ? hl + 1: hr + 1;
}
}