[Leetcode Binary Tree Series] 2 Level Traversal of Binary Tree

344d69c84a85bfcc2eac3c0807045139.gif


 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 Traversal

Given 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 analysis
  • Ideas

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.

fc2ac391ec93c42a4abcc6fb4a259865.png

  • Recycle elements from the queue. If the fetched element has left and right nodes, put the left and right nodes into the queue.

    53b65a5cde88be95942f6da4ee828efb.png



02 code implementation

1c++ version

2e52ebc5e2e30cfa0bbc590fa9b77c3b.jpeg

2python version

b1c6e33b2422250d7be536b3f135b990.jpeg

3java version

a9a6eff4661c7a6f059f7055b3ed6d79.jpeg




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.

c36f9bcf6ddeec68f5119c0e5ee5520a.jpeg


Guess you like

Origin blog.51cto.com/14984904/2545486