Title Description
Operates a given two-fork tree and transforms it into a mirror of the source binary tree.
Input Description:
Image definition of binary tree: source binary tree 8 /6 x / \ 5 7 9 Mirror binary tree 8 / 6 /\ / 9 7 5
Title Address
https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&rp=3&ru=/ta/ Coding-interviews&qru=/ta/coding-interviews/question-ranking
Ideas
Idea 1: Recursive, determine whether the root node is empty, is empty, no exchange, not empty, exchange its left and right nodes. Recursive to left and right subtrees.
#-*-coding:utf-8-*-classTreeNode:def __init__(self,x): Self.val=x self.left=None self.right=Nonenode1= TreeNode (8) Node2= TreeNode (6) Node3= TreeNode (10) Node4= TreeNode (5) Node5= TreeNode (7) Node6= TreeNode (9) Node7= TreeNode (11) Node1.left=Node2node1.right=Node3node2.left=Node4node2.right=Node5node3.left=Node6node3.right=Node7classSolution:#returns the root node of the mirror tree defMirror (self, root):#Recursive if notRoot:returnTemp=Root.left Root.left=root.right root.right=Temp#if Root.left:Self . Mirror (Root.left)#if Root.right:Self . Mirror (root.right)returnRootif __name__=='__main__': Result=solution (). Mirror (Node1)Print(Result)
The sword refers to offer 18. Image of Binary tree (binary tree)