• [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.

    Hide Tags
     Tree Depth-first Search
     
        这题是找二叉树的最小深度,这是广度搜索比较好吧,为啥提示给的是 深度优先呢。
    1. 判断树是否为空
    2. 将root 节点压入队列
    3. while 队列不为空
    4. 计算当前队列的个数,进行这么多次的第5步
    5. 获取queue 头,弹出一个,判断弹出的时候为叶子,是的返回,不是将支点加入队列
     1 #include <iostream>
     2 #include <queue>
     3 using namespace std;
     4 /**
     5  * Definition for binary tree
     6  */
     7  struct TreeNode {
     8      int val;
     9      TreeNode *left;
    10      TreeNode *right;
    11      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    12  };
    13 
    14 class Solution {
    15 public:
    16     int minDepth(TreeNode *root) {
    17         if(root ==NULL) return 0;
    18         queue<TreeNode* > qu;
    19         TreeNode * curNode;
    20         qu.push(root);
    21         int ret =0;
    22         while(!qu.empty()){
    23             ret ++;
    24             int n = qu.size();
    25             while(n-->0){
    26                 curNode =qu.front();
    27                 qu.pop();
    28                 if(curNode->left==NULL&&curNode->right==NULL)   return ret;
    29                 if(curNode->left!=NULL) qu.push(curNode->left);
    30                 if(curNode->right!=NULL)    qu.push(curNode->right);
    31             }
    32         }
    33         return ret;
    34     }
    35 };
    36 
    37 int main()
    38 {
    39 
    40     Solution sol;
    41     return 0;
    42 }
    View Code
  • 相关阅读:
    分页实现
    jquery扩展提示框
    可拖拽可扩展面板
    单表查询结果转换成泛型集合
    压缩远程图片并返回
    windows下python安装架包的问题
    从网络上下载数据
    自己实现jquery
    如何利用拼音首字母查询数据库
    正则表达式
  • 原文地址:https://www.cnblogs.com/Azhu/p/4149754.html
Copyright © 2020-2023  润新知