Python 中的对称树
假设我们有一个二叉树。我们必须检查这棵树是不是对称树。当我们获取它的镜像时,如果一棵树保持不变,那么它将被称作对称树。对于这棵树,第一棵是对称的,但第二棵不是。
要解决这个问题,我们将遵循以下步骤。
- 我们将递归地调用以下步骤。该函数将是 solve(root, root)
- 如果 node1 和 node2 为空,则返回 true
- 如果 node1 或 node2 为空,则返回 false
- 当 node1.val = node2.val 并且 solve(node1.left, node2.right) 以及 solve(node1.right, node2.left) 返回 true 时
让我们看一下以下实现以获得更好的理解 -
示例
class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): if data is not None: temp.left = TreeNode(data) else: temp.left = TreeNode(0) break else: que.append(temp.left) if (not temp.right): if data is not None: temp.right = TreeNode(data) else: temp.right = TreeNode(0) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ return self.solve(root,root) def solve(self,node1,node2): if not node1 and not node2: return True if not node1 or not node2: return False # print(node1.val, node2.val) return node1.data == node2.data and self.solve(node1.left,node2.right) and self.solve(node1.right,node2.left) tree1 = make_tree([1,2,2,3,4,4,3]) tree2 = make_tree([1,2,2,3,4,None,3]) ob1 = Solution() print(ob1.isSymmetric(tree1)) print(ob1.isSymmetric(tree2))
输入
tree1 = make_tree([1,2,2,3,4,4,3]) tree2 = make_tree([1,2,2,3,4,None,3])
输出
True False
广告