Table of contents
2. How to use [-1], [:-1], [::-1], [n::-1] in python
1. Topic:
Given the root node root of a binary tree, check if it is axisymmetric.
Example 1:
Input: root = [1,2,2,3,4,4,3]
Output: true
Example 2:
Input: root = [1,2,2,null,3,null,3]
Output: false
hint:
The number of nodes in the tree is in the range [1, 1000]
-100 <= Node.val <= 100
2. Ideas:
1. tree
You can take a look at this article to understand the expression of trees in python.
Tree --- python implementation
Knowing the structure of the tree, it is essentially to compare whether the two nodes located on the left and right are the same.
Add a knowledge:
2. How to use [-1], [:-1], [::-1], [n::-1] in python
import numpy as np
a=np.random.rand(5)
print(a)
[ 0.64061262 0.8451399 0.965673 0.89256687 0.48518743]
print(a[-1]) ###take the last element
[0.48518743]
print(a[:-1 ]) ### Get all except the last one
[ 0.64061262 0.8451399 0.965673 0.89256687]
print(a[::-1]) ### Get the elements from back to front (opposite)
[ 0.48518743 0.89256687 0.965673 0.8451399 0. 64061262]
print(a[ 2::-1]) ### Take the element whose subscript is 2 and read
[ 0.965673 0.8451399 0.64061262]
3. Specific ideas:
method one:
We can use the method of layer traversal, layer order traversal to find out, and judge whether each layer is a palindrome array.
Note: The difference from ordinary layer order traversal is that if it is an empty node, None must also be added to the result array of layer order traversal.
Method Two:
The second method is a recursive method. The core idea is to compare two nodes from left to right to see if they are the same.
3. Code:
method one:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
queue=[root]
while queue:
next_queue=[]
now_queue=[]
for node in queue:
if not node:
now_queue.append(None)
continue
next_queue.append(node.left)
next_queue.append(node.right)
now_queue.append(node.val)
if now_queue!=now_queue[::-1]:
return False
queue=next_queue
return True
Method Two:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def check(node1, node2):
if not node1 and not node2:
return True
elif not node1 or not node2:
return False
if node1.val != node2.val:
return False
return check(node1.left, node2.right) and check(node1.right, node2.left)
return check(root, root)