算法数据结构——数的深搜和广搜(dfs和bfs)

时间:2020-05-22
本文章向大家介绍算法数据结构——数的深搜和广搜(dfs和bfs),主要包括算法数据结构——数的深搜和广搜(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 };

3. 深搜,非递归

原文地址:https://www.cnblogs.com/qiezi-online/p/12935497.html