原题如下
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.
思路
因为是要找最小深度,所以只需从上往下搜索,直到到达某一层的一个节点没有左右节点为止。相比深度优先搜索,用宽度优先搜索大约平均可以减少一半的搜索数量。可以用vector做队列使用。
代码
class Solution {
public:
int minDepth(TreeNode* root) {
int depth = 0;
vector< pair<TreeNode*, int> > a; // 节点和深度构成的二元组
if(root == NULL) return 0;
a.push_back(make_pair(root, 1));
TreeNode* node = root;
while(!a.empty()){
node = a.front().first; // 当前搜索节点
depth = a.front().second; // 当前深度
// 左右节点为空则搜索结束
if(node->left == NULL && node->right == NULL)
break;
if(node->left != NULL){
a.push_back(make_pair(node->left, depth + 1));
}
if(node->right != NULL)
a.push_back(make_pair(node->right, depth + 1));
a.erase(a.begin()); // 队首出队列
}
return depth;
}
};