BFS----二叉树搜索最小深度
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
Cpp:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <queue>
#include <set>
#include <vector>
using namespace std;
class Solution {
public:
int DFS(TreeNode *root)
{
queue<TreeNode*> q; // 对节点进行遍历
q.push(root);
int dep = 1;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode *tmp = q.front();
q.pop();
// 终止条件找到第一个叶子节点,也就是最小节点,dfs常用于寻找最小路径
if (tmp->left == NULL && tmp->right == NULL) {
return dep;
}
// 下一层需要遍历的元素,不需要产生剪枝,不会进行重复搜索
if (tmp->left != NULL) {
q.push(tmp->left);
}
if (tmp->right != NULL) {
q.push(tmp->right);
}
}
dep++;
}
return dep;
}
int minDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
return DFS(root);
}
};