Leetcode题目:Minimum Depth of Binary Tree
题目:
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.
题目解答:
这道题借助了之前做的层次遍历的题目的代码,增加了一个判断条件,如果可以确定当前节点是叶子节点,则返回其深度,也就是找到的最近的叶子节点的深度。
代码如下:
/**
* 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) {
int depth = 0;
int curnum = 0;
int childnum = 0;
if(root == NULL)
{
return 0;
}
queue<TreeNode *> TreeQueue;
TreeQueue.push(root);
curnum = 1;
while(curnum != 0)
{
vector<int> tmp;
depth++;
while(curnum != 0)
{
TreeNode *p = TreeQueue.front();
tmp.push_back(p -> val);
if((p -> left == NULL) && (p -> right == NULL))
{
return depth;
}
if(p -> left != NULL)
{
TreeQueue.push(p -> left);
childnum++;
}
if(p -> right != NULL)
{
TreeQueue.push(p -> right);
childnum++;
}
TreeQueue.pop();
curnum--;
}
curnum = childnum;
childnum = 0;
}
return depth;
}
};
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步