[leetcode]: 111. Minimum Depth of Binary Tree

爱被打了一巴掌 2022-06-14 19:54 294阅读 0赞

1.题目

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.
求一棵二叉树的最小深度。
最小深度的定义为根节点到叶子节点的最小距离

2.分析

广度优先遍历,BFS。
相当于从根节点开始,一层一层往下遍历,当遍历到第一个叶子节点时,所得到的深度是最小的。

3.代码

BFS

  1. class Solution {
  2. public:
  3. int minDepth(TreeNode* root) {
  4. if (root == NULL)
  5. return 0;
  6. queue<pair<TreeNode*,int>> nodes;
  7. nodes.push(make_pair(root, 1));
  8. int depth = 0;
  9. while (!nodes.empty()) {
  10. TreeNode* node = nodes.front().first;
  11. depth = nodes.front().second;
  12. nodes.pop();
  13. if (node->left)
  14. nodes.push(make_pair(node->left, depth + 1));
  15. if (node->right)
  16. nodes.push(make_pair(node->right, depth + 1));
  17. if (!node->left && !node->right)//叶子节点
  18. return depth;
  19. }
  20. }
  21. };

发表评论

表情:
评论列表 (有 0 条评论,294人围观)

还没有评论,来说两句吧...

相关阅读