zoukankan      html  css  js  c++  java
  • 算法数据结构——数的深搜和广搜(dfs和bfs)

    leetcode104 二叉树的最大深度 https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

     深度搜索分两种:递归(使用栈)

     广度搜索:非递归(使用队列)

    1. 广度搜索bfs:(标准模板)(也可建议用c++的queue,deque是双端队列,可以实现头尾的插入和弹出)

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxDepth(TreeNode* root) {
    13         deque<TreeNode*> d;
    14         if(!root)
    15         return 0;
    16         d.push_back(root);
    17         int num = 0;
    18         while(!d.empty())
    19         {
    20             int t = d.size();
    21             //cout<<"t:"<<t<<endl;
    22             for(int i=0;i<t;i++)
    23             {
    24                 TreeNode *p = d.front();
    25                 d.pop_front();
    26                 if(p->left)
    27                 d.push_back(p->left);
    28                 if(p->right)
    29                 d.push_back(p->right);
    30             }
    31             num++;
    32         }
    33         return num;
    34     }
    35 };

    2. 深搜,递归

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     int maxDepth(TreeNode* root) {
    13         if(!root)
    14         return 0;
    15 
    16         return max(maxDepth(root->left), maxDepth(root->right)) +1;
    17     }
    18 };
  • 相关阅读:
    python虚拟环境--virtualenv
    求导法则和高阶导数
    restful规范
    python协程--yield和yield from
    打印质数
    更改docker的存储位置
    同台ECS安装多个mysql
    jenkins + gitlab + harbor + k8s 部署项目
    jenkins 配置maven
    gitlab + jenkins 持续集成
  • 原文地址:https://www.cnblogs.com/qiezi-online/p/12935497.html
Copyright © 2011-2022 走看看