Wins the Offer (XVIII): binary tree mirror

Wins the Offer (XVIII): binary tree mirror

Search micro-channel public number: 'AI-ming3526' or 'this small computer vision' for more algorithms, machine learning, dry
CSDN: https://blog.csdn.net/baidu_31657889/
GitHub: https://github.com/ aimi-cn / AILearners

First, the primer

This series is my brush "to prove safety Offer" brush off the cattle in question notes online, it aims to enhance the ability under its own algorithm.
View the complete algorithm to prove safety issues resolved Offer Click: to prove safety Offer complete analytical exercises

Second, the title

Operation of a given binary tree, the binary tree is converted into a source image.

The binary image is defined:

file

1, ideas

After the first exchange of two child nodes of the root node, we noticed that the child node is node 10,6 remain the same, so we also need to exchange about child node of the two nodes. After doing these two exchanges, we have done through all the non-leaf node. At this point after the conversion tree is just a mirror of the original tree. Switching mode is shown below:

file

So we can do first two child nodes sequentially switched below the root node, the exchange done about recursive call node will eventually transform the entire binary tree Mirrors -

2, programming

python2.7

Code implementation:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if not root:
            return root
        else:
            root.left,root.right = root.right,root.left
            self.Mirror(root.left)
            self.Mirror(root.right)
            return root

AIMI-CN AI learning exchange group [1015286623] For more information on AI
scan code plus group:

file

Sharing technology, fun in life: our number of public computer vision this small push "AI" series News articles per week, welcome your interest!

file

Guess you like

Origin www.cnblogs.com/aimi-cn/p/11404044.html