广度优先搜索算法BFS

BFS介绍

类似于二叉树层序遍历,先遍历同一深度的结点,遍历完后再向不同深度遍历

PS:(视频看了千千遍都看不明白,果然学习算法最快的方法就是刷题…)

LeetCode面试题 04.03. 特定深度节点链表

给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

示例:

输入:[1,2,3,4,5,null,7,8]

       1
  	  /  \ 
 	 2    3
 	/  \   \ 
   4   5    7    
  /   
 8

输出:[[1],[2,3],[4,5,7],[8]]

思路:

递归+队列实现简单的BFS

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<ListNode*> listOfDepth(TreeNode* tree) {
    
    
        vector<ListNode*> ans;
        queue<TreeNode*> q;
        q.push(tree);
        while(!q.empty()){
    
    
            int size=q.size();
            TreeNode *node;
            ListNode *head,*prev,*curr;
            for(int i=0;i<size;++i){
    
    
                node=q.front();
                q.pop();
                if(i==0){
    
    
                    head=new ListNode(node->val);
                    prev=head;
                }
                else{
    
    
                    curr=new ListNode(node->val);
                    prev->next=curr;
                    prev=prev->next;
                }
                if(node->left)
                    q.push(node->left);
                if(node->right)
                    q.push(node->right);
            }
            ans.push_back(head);
        }
        return ans;

    }
};

猜你喜欢

转载自blog.csdn.net/qq_43477024/article/details/111717270