LeetCode using Ric Tree
LeetCode-Based Semantic Tree
Original question
Determine whether a tree is symmetrical. It is best to provide both recursive and iterative solutions.
Note:
None
Example:
Input:
1 / \ 2 2 / \ / \3 4 4 3
Output: True
Input:
1 / \ 2 2 \ \ 3 3
Output: False
Solutions
To check whether A binary tree is symmetric, first check whether the Left and Right nodes A and B of the root node have the same value. If the values of A and B are equal, then we need to continue to judge whether the left node of A is symmetric with the right node of B and the right node of A and the left node of B. In this way, we can recursively obtain the result. To solve this problem through iterative methods, place vertices that need to be judged to be symmetric in order (pay attention to which nodes need to be determined to be equal) in two stacks, and continue to determine the stack and pressure stack.
AC Source Code
# Definition for a binary tree node.class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = Noneclass Solution(object): # Solve it recursively def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True return self._isSymmetric(root.left, root.right) def _isSymmetric(self, left, right): if not left and not right: return True if not left or not right: return False if left.val != right.val: return False return self._isSymmetric(left.left, right.right) and self._isSymmetric(left.right, right.left) # Solve it iteratively def isSymmetric_iterate(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True stack1, stack2 = [], [] stack1.append(root.left) stack2.append(root.right) while stack1 and stack2: size1 = len(stack1) size2 = len(stack2) if size1 != size2: return False for __ in range(size1): curr1, curr2 = stack1.pop(), stack2.pop() if not curr1 and not curr2: continue if not curr1 or not curr2: return False if curr1.val != curr2.val: return False stack1.append(curr1.left) stack1.append(curr1.right) stack2.append(curr2.right) stack2.append(curr2.left) return not stack1 and not stack2if __name__ == "__main__": None