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 };
  • 相关阅读:
    ANSI C 与 C99的不同
    字符串中含有空格的注意事项
    巧用printf函数
    求数列的和
    数值统计
    平方和与立方和
    求奇数的乘积
    第几天?
    细节之重
    用%*c滤掉回车,ASCII码排序
  • 原文地址:https://www.cnblogs.com/qiezi-online/p/12935497.html
Copyright © 2011-2022 走看看