111. Minimum Depth of Binary Tree
problem description
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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its minimum depth = 2.
algorithm thought
得到最浅的叶子节点的深度,直接用广度优先搜索即可,广度优先搜索有找的极值的性质
code
/**
* 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==NULL)
return 0;
queue<TreeNode*> qu;
qu.push(root);
TreeNode* pos=new TreeNode(-1);
qu.push(pos);
int res=1;
while(!qu.empty()){
TreeNode* fr=qu.front();
qu.pop();
if(fr==NULL)
continue;
if(fr==pos){
qu.push(pos);
res++;
continue;
}
if(isleaf(fr))
return res;
qu.push(fr->left);
qu.push(fr->right);
}
return res;
}
bool isleaf(TreeNode* root){
return (root->right==NULL)&&(root->left==NULL);
}
};
algorithm analysis
如果用深度优先搜索做这个题目,最后时间复杂度会是O(n),因为会遍历所有节点,最后得到最浅的叶子节点。但是用广度优先搜索,只要找到第一个叶子节点就会返回,所以时间复杂度是降低很多的,不过应该也是O(n)
Last updated