LeetCode OJ 111. Minimum Depth of Binary Tree

时间:2023-03-08 18:14:56

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 a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0; int leftmin = minDepth(root.left);
int rightmin = minDepth(root.right); if(leftmin==0) return rightmin + 1;
if(rightmin==0) return leftmin + 1;
return leftmin>rightmin?rightmin+1:leftmin+1;
}
}