This article involves knowledge points
Level traversal of binary tree
Use of queues
The traversal of the binary tree and the related concepts of the queue have been introduced before, and the forgotten friends will definitely double the effect after reviewing!
Review of Binomial Tree Knowledge: [ Today, add a BGM to the Binomial Tree, the Binomial Tree is singing! ]
Queue knowledge review: [leetcode stack queue] 1 stack implementation queue
1Leetcode102 Binary Tree Level TraversalGiven a binary tree, which is returned by the level node traversed values. (That is, visit all nodes from left to right layer by layer).
Example 1:
E.g:
Given a binary tree: [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
Return the result of its level traversal:
[ [3], [9,20], [15,7] ]
Xiaolan hopes everyone will think about it for 1 minute
The effect is better!
0 1 Question analysisIdeas
Idea statement
Hierarchical traversal, as the name implies, visits layer by layer, from the first layer to the nth layer, that is, the classmates and aunts who line up first eat first (you have to jump in the queue, you have to look better? Priority queue?). Ok, this is first-in, first-out. Hey, through the previous study, you must know that you need a queue.
To access from the root node, put the root node into the queue first, and record the number of nodes in the current layer.
Recycle elements from the queue. If the fetched element has left and right nodes, put the left and right nodes into the queue.
02 code implementation
1c++ version 2python version 3java version
Warm man told
If you make a little progress with Xiaolan every day, your life will be better!
Enter algorithm, interview learning group, and grow together!
Pay attention to the bottom and reply "Enter the group" to enter our team.