题解C
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
# define min(A,B) ((A)<(B)?(A):(B))
int minDepth(struct TreeNode* root){
if(root==NULL){
return 0;
}
if(root->left==NULL){
return minDepth(root->right)+1;
}else if(root->right==NULL){
return minDepth(root->left)+1;
}
return min(minDepth(root->left),minDepth(root->right)) + 1;
}
题解Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
if((root.left==null) && (root.right==null)){
return 1;
}
int min_depth = Integer.MAX_VALUE;
if(root.left!=null){
min_depth = Math.min(minDepth(root.left),min_depth);
}
if(root.right!=null){
min_depth = Math.min(minDepth(root.right),min_depth);
}
return min_depth + 1;
}
}
相关知识
Integer.MAZ_VALUE:表示int所能表示的最大值0x7fffffff
相对应的Integer.MIN_VALUE:表示int所能表示的最小值0x80000000