- 111. Minimum Depth of Binary Tre
- leetcode:111. Minimum Depth of B
- Leetcode 111. Minimum Depth of B
- Leetcode 111. Minimum Depth of B
- leetcode 111. Minimum Depth of B
- LeetCode 111. Minimum Depth of B
- LeetCode 111. Minimum Depth of B
- Minimum Depth of Binary Tree
- [二叉树]111. Minimum Depth of Binar
- 二叉树的最小、最大深度以及平衡二叉树
0. 题目
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.
![]()
1. C++版本
思想:借助层次遍历,只统计既没有左子树,也没有右子树的节点的深度,从中去除最小深度。对于最小深度这种题目,就考虑用宽度优先算法,而对于最大深度,就用深度优先算法
int minDepth(TreeNode* root) {
queue<TreeNode*> fatherQueue, childQueue;
int depth = 1, minDepth=0;
bool isFirst = true;
if (root) {
fatherQueue.push(root);
}
while (!fatherQueue.empty()) {
TreeNode* currNode = fatherQueue.front();
fatherQueue.pop();
if (!currNode->left && !currNode ->right) {
if (isFirst) {
minDepth = depth;
isFirst = false;
}
else if(!isFirst && depth < minDepth)
minDepth = depth;
}
if (currNode->left) {
childQueue.push(currNode->left);
}
if (currNode->right) {
childQueue.push(currNode->right);
}
if (fatherQueue.empty() && !childQueue.empty()) {
swap(fatherQueue, childQueue);
depth += 1;
}
}
return minDepth;
}
网友评论