155. 二叉树的最小深度
描述
给定一个二叉树,找出其最小深度。
二叉树的最小深度为根节点到最近叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最小深度为 2
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree
* @return: An integer
*/
//递归方式
int minDepth(TreeNode * root) {
if (root == NULL) return 0;
int l = minDepth(root->left);
int r = minDepth(root->right);
if (root->left == NULL) return r+1;
if (root->right== NULL) return l+1;
return (l>r? r:l) + 1;
}
//循环方式(BFS)
int minDepth(TreeNode * root) {
if (root == NULL ) return 0;
int depth = 1, p = 1;
std::deque<TreeNode*> lay;
lay.push_front(root);
while (!lay.empty()) {
int q = 0;
while (p) {
TreeNode* tmp = lay.back();
lay.pop_back();
--p;
TreeNode* l = tmp->left;
TreeNode* r = tmp->right;
if (l == NULL && r == NULL) return depth;
else if (l == NULL) {
lay.push_front(r);
++q;
} else if (r == NULL) {
lay.push_front(l);
++q;
} else {
lay.push_front(l);
lay.push_front(r);
q+=2;
}
}
++depth;
p = q;
}
}
};