标签:main 递归 on() interview clip mirror init pid utf-8
操作给定的二叉树,将其变换为源二叉树的镜像。
二叉树的镜像定义:源二叉树 8 / 6 10 / \ / 5 7 9 11 镜像二叉树 8 / 10 6 / \ / 11 9 7 5
题目地址
https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
思路
思路1:递归,判断根节点是否为空,为空时,无需交换,不为空时,交换其左右节点。对左右子树进行递归。
# -*- coding:utf-8 -*- class TreeNode: def __init__(self,x): self.val = x self.left = None self.right = None node1 = TreeNode(8) node2 = TreeNode(6) node3 = TreeNode(10) node4 = TreeNode(5) node5 = TreeNode(7) node6 = TreeNode(9) node7 = TreeNode(11) node1.left = node2 node1.right = node3 node2.left = node4 node2.right = node5 node3.left = node6 node3.right = node7 class Solution: # 返回镜像树的根节点 def Mirror(self, root): # 递归 if not root: return temp = root.left root.left = root.right root.right = temp # if root.left: self.Mirror(root.left) # if root.right: self.Mirror(root.right) return root if __name__ == ‘__main__‘: result = Solution().Mirror(node1) print(result)
标签:main 递归 on() interview clip mirror init pid utf-8
原文地址:https://www.cnblogs.com/huangqiancun/p/9784305.html