leetcode (the offer to prove safety) plane of symmetry 28. The binary tree questions (Python)

Here Insert Picture Description
Solution:
two methods to solve a recursive process (the DFS), one is the iterative method (BFS)
recursion:
Thought recursion in that left and right subtrees corresponding to a node is therefore provided two paths ( two pointers) to access, view whether the left and right subtrees corresponding to equal.
Recursive termination condition:

  1. If the two nodes are None, returns True
  2. If one of None, not a return False
  3. If the corresponding value is not equal, returns False
class Solution:
    def isSymmetric(self, root):
    	if not root:
    		return True

    	def dfs_double(A1,A2):

    		if A1 == None and A2 == None:
    			return True

    		if A1 == None or A2 == None:
    			return False
    		if A1.val != A2.val:
    			return False

    		return (dfs_double(A1.left,A2.right)
    		and dfs_double(A1.right,A2.left))

    	de = dfs_double(root.left,root.right)
    	return de

Iterative method:
similar iterative method of thought and recursion, but this time set up two queues, a queue began a visit to the left node, a node from the right queue began a visit, to see the corresponding values are equal.
I thought this question of the nature of borrowing symmetrical binary tree. (I.e. The tree after switching nodes about the same as the original tree)

class Solution:
    def isSymmetric(self, root):

    	if not root:
    		return True

    	queque = [root]
    	queque1 = [root]#双枝

    	while (queque and queque1):

    		tmp = queque.pop(0)
    		tmp1 = queque1.pop(0)
    		# print(tmp.val)
    		# print('tmp1 %d' % tmp1.val)
    		if (tmp == None and tmp1 != None) or (tmp != None and tmp1 == None):
    			return False
    		if tmp == None and tmp1 == None:
    			continue
    		elif tmp.val != tmp1.val:
    			return False

    		if queque == None or queque1 == None:
    			return False
    		print(tmp)
    		print('tmp1, %d' % tmp1)
    		
    		queque.append(tmp.left)

    		
    		queque.append(tmp.right)

    		

    		queque1.append(tmp1.right)

    		

    		queque1.append(tmp1.left)

    	return True
Published 100 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/cy_believ/article/details/104506951