Breadth First Search Algorithm BFS

BFS introduction

Similar to binary tree hierarchy traversal, nodes of the same depth are traversed first, and then to different depths after traversal

PS: (After watching the video a thousand times, I can’t understand it. Sure enough, the fastest way to learn an algorithm is to write questions...)

LeetCode Interview Questions 04.03. Linked List of Specific Depth Nodes

Given a binary tree, design an algorithm to create a linked list containing all nodes at a certain depth (for example, if the depth of a tree is D, then D linked lists will be created). Returns an array of linked lists of all depths.

Example:

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

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

Output: [[1],[2,3],[4,5,7],[8]]

Ideas:

Implement simple BFS with recursion + queue

Code:

/**
 * 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;

    }
};

Guess you like

Origin blog.csdn.net/qq_43477024/article/details/111717270