The sword refers to offer 18. Image of Binary tree (binary tree)

Source: Internet
Author: User

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 Coding-interviews&qru=/ta/coding-interviews/question-ranking

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.