您的位置:首页 > 其它

leetcode dfs Minimum Depth of Binary Tree

2014-10-11 16:00 309 查看


Minimum Depth of Binary Tree

 Total Accepted: 25609 Total
Submissions: 86491My Submissions

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.

题意:求出二叉树的最小深度

思路:

minDepth(root) = 1 + min(minDepth(root->left), minDepth(root->right));

但如果 root -> left 或 root->right为空时,minDepth对他们的计算结果为返回 0 ,所以这两个要分别处理一下。

复杂度: 时间O(n) ,空间O(log n)

int minDepth(const TreeNode *root){
if(!root) return 0;
if(!root->left) return 1 + minDepth(root->right);
if(!root->right) return 1 + minDepth(root->left);
return 1 + min(minDepth(root->left), minDepth(root->right));
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: