1. 代码比文字更直观
2. 文字描述:新建一个二叉树,利用递归法,将源二叉树上的左节点赋值到新二叉树的右节点,将源二叉树上的右节点赋值到新二叉树的左节点。
# 方式1:生成新的镜像二叉树def getMirrorBST(self, root): if root == None: return newTree = treeNode(root.val) newTree.right = self.getMirrorBST(root.left) newTree.left = self.getMirrorBST(root.right) return newTree
但是提交代码后,说通过率为0… 原来要求将原有的二叉树就地改成镜像二叉树…如此一来,代码就更简单了:因为交换根节点的左右子节点时,以左右子节点为根节点的左子树和右子树也会交换位置。最终的Python代码如下:
# 方式2:改变给定的二叉树为镜像二叉树def turnToMirror(self, root): if root == None: return root.right, root.left = root.left, root.right self.turnToMirror(root.left) self.turnToMirror(root.right) return root
class Solution: # 给定一个二叉树,获得其镜像(轴对称)的镜像二叉树: # 方式1:生成新的镜像二叉树 def getMirrorBST(self, root): if root == None: return newTree = treeNode(root.val) newTree.right = self.getMirrorBST(root.left) newTree.left = self.getMirrorBST(root.right) return newTree # 方式2:改变给定的二叉树为镜像二叉树 def turnToMirror(self, root): if root == None: return root.right, root.left = root.left, root.right self.turnToMirror(root.left) self.turnToMirror(root.right) return root # 给定二叉树的前序遍历和中序遍历,获得该二叉树 def getBSTwithPreTin(self, pre, tin): if len(pre)==0 | len(tin)==0: return None root = treeNode(pre[0]) for order,item in enumerate(tin): if root .val == item: root.left = self.getBSTwithPreTin(pre[1:order+1], tin[:order]) root.right = self.getBSTwithPreTin(pre[order+1:], tin[order+1:]) return rootclass treeNode: def __init__(self, x): self.left = None self.right = None self.val = xif __name__ == '__main__': flag = "turnToMirror" solution = Solution() preorder_seq = [1, 2, 4, 7, 3, 5, 6, 8] middleorder_seq = [4, 7, 2, 1, 5, 3, 8, 6] treeRoot1 = solution.getBSTwithPreTin(preorder_seq, middleorder_seq) if flag == "mirrorBST": newRoot = solution.getMirrorBST(treeRoot1) print(newRoot) if flag == "turnToMirror": solution.turnToMirror(treeRoot1) print(treeRoot1)