DFS、BFS专项

DFS、BFS专项

1. 二叉树的最大深度(思路应该没问题,语法好像有错误)

题目描述

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

解题思路

思路1:DFS搜索

  1. 若二叉树为空,直接输出0。否则进入2。
  2. 将二叉树传入DFS,判断左右结点是否均为空,若均为空,则比较目前最大的深度,取较大值更新它;否则,将不为空的结点再次传入DFS。

源代码

#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
//int main()
//{
    
    
//	
//	return 0;
//} 
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <cmath>
struct TreeNode {
    
    
    int val;
    TreeNode *left;
    TreeNode *right;
	//    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


int maxDeep = 0;
void DFS(TreeNode* root, int tmpDeep)
	{
    
    
		tmpDeep++;
		if(!root->left && !root->right)
		{
    
    
			maxDeep = max(tmpDeep, maxDeep);
            cout << "分支1" << endl;
		}
		else if(root->left)
		{
    
    
			DFS(root->left, tmpDeep);
            cout << "分支2" << endl;
		}
		else if(root->right)
		{
    
    
			DFS(root->right, tmpDeep);
            cout << "分支3" << endl;
		}
	}
   	
    int main() {
    
    
    	TreeNode* root;
    	root->left = NULL;
    	root->right = NULL;
    	root->val = 1;
    	int tmpDeep = 0;
        if(!root)
		{
    
    
			cout << "0" << endl;
            return 0;
		} 
		else 
		{
    
    
			cout << "//" << endl;
		 	DFS(root, tmpDeep);
            cout << "--" << endl;
		 	cout << maxDeep << endl;
		}
		cout << maxDeep << endl;
        return maxDeep;
    }

题型分析

  1. 典型DFS题,若题目中有涉及深度、广度的题,均可新建一个搜索在做。

下次遇到此类题我要注意的地方

1. 看到深度,立刻反应是深度搜索题。2. max函数在cmath库中+using namespace std

时间、空间复杂度

tf:n
kf:n

此类题模板代码

		if(!root->left && !root->right)
		{
    
    
			maxDeep = max(tmpDeep, maxDeep);
            cout << "分支1" << endl;
		}
		else if(root->left)
		{
    
    
			DFS(root->left, tmpDeep);
            cout << "分支2" << endl;
		}
		else if(root->right)
		{
    
    
			DFS(root->right, tmpDeep);
            cout << "分支3" << endl;
		}

总结(用个等式)

二叉树的最大深度 = DFS左右结点遍历 + 时间复杂度为n

题目描述

解题思路

思路1:

源代码

题型分析

下次遇到此类题我要注意的地方

时间、空间复杂度

此类题模板代码

总结(用个等式)

题目描述

解题思路

思路1:

源代码

题型分析

下次遇到此类题我要注意的地方

时间、空间复杂度

此类题模板代码

总结(用个等式)

题目描述

解题思路

思路1:

源代码

题型分析

下次遇到此类题我要注意的地方

时间、空间复杂度

此类题模板代码

总结(用个等式)

题目描述

解题思路

思路1:

源代码

题型分析

下次遇到此类题我要注意的地方

时间、空间复杂度

此类题模板代码

总结(用个等式)

猜你喜欢

转载自blog.csdn.net/qq_40092110/article/details/106073705