[leetcode binary tree series] 4 symmetrical binary tree

344d69c84a85bfcc2eac3c0807045139.gif


 This article involves knowledge points 

  • 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

1Leetcode101 Symmetric Binary Tree

Given a binary tree, check whether it is mirror-symmetrical.





Example 1:

For example, the binary tree  [1,2,2,3,4,4,3] is symmetric.

    1
   / \
  2   2
 / \ / \
3  4 4  3
 
 

But the following  [1,2,2,null,3,null,3] is not mirror symmetry:

    1
   / \
  2   2
   \   \
   3    3




Xiaolan hopes everyone will think about it for 1 minute

The effect is better!

0 1 Question analysis
  • Ideas

Idea statement

If it is a symmetric binary tree, the values ​​of its consecutive left and right child nodes are equal. We enqueue two nodes first, then take out two nodes from the queue each time, and finally enqueue its left and right child nodes in the reverse order. The judgment ends when the queue is empty. Draw the picture below to understand.

  • To access from the root node, first put the left and right nodes of the root node into the queue.

c2f8b578e8badc3d5744b2622a1e166a.png

  • Take two elements from the queue. Compare the left child of the left node with the right child of the right node in the following figure, the leftmost node with a value of 35 and the rightmost node with a value of 35 (green node).

    607307ae034cc355b4cf2c52c36401fd.png


02 code implementation

1c++ version

4ea67d2ed7b8261ba95cda924038fb1d.jpeg

2python version

43c57a8f63ceee2df87a3fd1af6823ce.jpeg

3java version

29f894096c80fd8628a69cc6dd13960f.jpeg


Guess you like

Origin blog.51cto.com/14984904/2545488