Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
29 lines (24 sloc) 722 Bytes
problem:
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.
-----------------------------------------------------------
solution:
//////////////////////////////////
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//求最浅深度要注意是二叉树是单枝时的情况
int minDepth(TreeNode *root)
{
if(root == NULL)
return 0;
int left = minDepth(root->left) + 1;
int right = minDepth(root->right) + 1;
if(left == 1 || right == 1)
return left > right ? left : right;
else
return left < right ? left : right;
}