Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

Determine whether the binary tree is symmetric

Problem description

Implement a function to determine whether a binary tree is symmetric. A binary tree is symmetric if it is the same as its mirror image.

Example: binary trees [1, 2, 2, 3, 4, 4, 3] are symmetric and binary trees [1, 2, 2, NULL, 3, NULL, 3] are not mirror symmetric:

To analyze problems

First, let’s look at the definition of a symmetric binary tree. A symmetric binary tree is one that satisfies the following conditions: For any two symmetric nodes L and R in the tree, there must be:

  • L.val = R. Val, that is, the values of the two symmetric nodes are equal.
  • Val = r.ight. Val, that is, the left child of L must have the same value as the right child of R.
  • Val = r.left. val, that is, the value of the right child of L should be equal to the value of the left child of R.

So, we can recurse from top to bottom, and then determine whether each pair of nodes is symmetric, thereby determining whether the tree is a symmetric binary tree.

Let’s look at the implementation of the code.

Class Solution: def isSymmetric(self, root): # Return True if not root: def is_recur(L, R): Return True if not L and not R: Return False if not L or not R or l.val! = R.val: Return False return is_recur(l.ight, r.ight) and is_recur(l.ight, r.ight) root.right)Copy the code

The time complexity and space complexity of this algorithm are O(N).