采用递归思想,这次是求最小深度。
(1)C语言实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int min(int x, int y){
return x<y?x:y;
}
int minDepth(struct TreeNode* root) {
if(!root)
return 0;
if(!root->left)
return 1+minDepth(root->right);
if(root->right==NULL)
return 1+minDepth(root->left);
return 1+min(minDepth(root->left), minDepth(root->right));
}
(2)C++实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root)
return 0;
if(!root->left)
return 1+minDepth(root->right);
if(!root->right)
return 1+minDepth(root->left);
return min(minDepth(root->left), minDepth(root->right))+1;
}
};
(3)java实现
/**
* 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;
if(root.left == null)
return 1+minDepth(root.right);
if(root.right == null)
return 1+minDepth(root.left);
return 1+Math.min(minDepth(root.left), minDepth(root.right));
}
}