Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize the linked list of nodes with specific depth by golang's skill of browsing leetcode

Shulou Source: shulou.com Published: 2022-06-01 12:47:51 09月28日 Update

This article mainly shows you the "golang brush leetcode skills how to achieve a specific depth of node linked list", the content is easy to understand, clear, hope to help you solve doubts, the following let the editor lead you to study and learn "golang brush leetcode skills how to achieve a specific depth node linked list" this article.

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, D linked lists will be created). Returns an array containing a linked list of all depths.

Example:

Input: [1, 2, 3, 4, 5, null7, 8]

one

/\

2 3

/\\

4 5 7

/

eight

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

Problem-solving ideas

1. This is a combined problem of sequence traversal of a tree + linked list, which mainly examines the understanding of tree, queue and linked list, as well as the comprehensive application of these data structures.

2. The sequence traversal of the tree needs the help of queues, and for each layer, two queues are needed.

When traversing, we pop up each node of the Q1 layer in turn and put it into the linked list

4, deposit the left and right children of each node into Q2 in turn

5, deposit Q2 into Q1

6, repeat 3-5 until each queue is empty.

Code implementation

/ * Definition for a binary tree node. * type TreeNode struct {* Val int * Left * TreeNode * Right * TreeNode *} * / * Definition for singly-linked list. * type ListNode struct {* Val int * Next * ListNode *} * / func listOfDepth (tree * TreeNode) [] * ListNode {var Q1 Q2 queue if tree==nil {return nil} var r [] * ListNode q1.push (tree) head:=new (ListNode) for! q1.empty () | |! q2.empty () {cur:=head for! q1.empty () {x:=q1.pop () if x.LeftSecretnil {q2.push (x.Left) } if x.Rightpercussionnil {q2.push (x.Right)} cur.Next=&ListNode {Val:x.Val } cur=cur.Next} r=append (rhead.Next) head.Next=nil for! q2.empty () {q1.push (q2.pop ())}} return r}

Type queue struct {data [] * TreeNode}

Func (this*queue) push (t*TreeNode) {this.data=append (this.data,t)}

Func (this*queue) empty () bool {return len (this.data)

Tags: Depth nodes queues skills content articles learning help one two code creative children ideas data data structures arrays time easy to understand more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei MariaDB vpn Shulou Tech Info Redmi