zoukankan      html  css  js  c++  java
  • LeetCode111_求二叉树最小深度(二叉树问题)

    题目:

    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.

    思路1:利用递归遍历,求最小深度

     1 //递归遍历求最小深度
     2 class Solution {
     3 public:
     4     int run(TreeNode *root) {
     5         if(root ==NULL) 
     6             return 0;
     7         int l = run(root->left);
     8         int r = run(root->right);
     9         if(l==0 || r==0)
    10             return l+r+1;
    11         return min(l, r) + 1;
    12     }
    13 };

    思路2:利用队列采用层序遍历,一旦找到一个叶节点,它肯定是最短的。

    参考链接:

    二叉树的层序遍历算法:https://blog.csdn.net/qq_29542611/article/details/79372678

     1 class Solution {
     2 public:
     3     int minDepth(TreeNode* root) {
     4         if(root == NULL) return 0; //处理边界情况,空树
     5         
     6         queue<TreeNode*> q;        //辅助数据结构-队列,用于层序遍历
     7         TreeNode* now = root;      //当前考察的节点,初始值为root
     8         TreeNode* last = root;     //所在层的最后一个节点,初始值为root
     9         int level = 1;             //返回值最小深度,初始值为1
    10         int size = 0;              //用于确定是否到达叶子节点
    11         
    12         q.push(root);               //根压入队列
    13         while(!q.empty())
    14         {
    15             now = q.front();
    16             q.pop();
    17             size = q.size();        //记录队列长度
    18             
    19             //左右孩子非空,压入队列
    20             if(now->left != NULL) 
    21                 q.push(now->left);
    22             if(now->right != NULL) 
    23                 q.push(now->right);
    24             
    25             //如果没有左右孩子入队,长度没有变化,说明这个节点是叶子节点,找到叶子节点,退出循环
    26             if(size == q.size())
    27                 break;
    28             
    29             //检查是否到达当前层最后一个节点,
    30             if(last == now)
    31             {
    32                 level++;
    33                 if(!q.empty())
    34                     //last指向下一层的最后一个节点
    35                     last = q.back();
    36             }
    37         }
    38         return level;
    39     }
    40 };

    C++队列Queue类成员函数如下:

    back()返回最后一个元素

    empty()如果队列空则返回真

    front()返回第一个元素

    pop()删除第一个元素

    push()在末尾加入一个元素

    size()返回队列中元素的个数

    总结:

    二叉树操作主要还是利用尾递归或者循环遍历这两种思路,进而涉及DFS(主要利用递归或者栈实现)或者BFS(主要利用队列实现)。剩下的只需要按照这些思路即可。

    广度优先BFS,深度优先DFS;

  • 相关阅读:
    Centos常用命令(四、进程)
    搭建git服务器(Centos7)
    tortoiseGit使用
    docker常用命令
    配置docker阿里云加速器_CentOS7
    Centos常用命令(三、网络配置)
    Centos常用命令(二、任务调度和磁盘管理)
    spring的作用
    什么是spring框架
    get和post的区别
  • 原文地址:https://www.cnblogs.com/grooovvve/p/10825748.html
Copyright © 2011-2022 走看看