当前位置:网站首页>[dai6] mirror image of JZ27 binary tree

[dai6] mirror image of JZ27 binary tree

2022-07-07 10:29:00 strawberry47

subject :

Operate a given binary tree , Transform it into a mirror image of the source binary tree .

Ideas

What returns is a tree , That has to be established TreeNode Well , Thought of two methods :
① Using the queue , Save from right to left node, The order read out in this way is mirrored ; But the answer requires outputting a tree , I don't know how to convert it into a tree
② Using recursion , When children are leaf nodes , Exchange the positions of the left and right nodes ; But I still can't write ,o(╥﹏╥)o

Secretly read the answer , Use the stack to store nodes , Exchange left and right nodes every time you take them out , So I wrote the code according to this idea :

# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#  The class name in the code 、 Method name 、 The parameter name has been specified , Do not modify , Return the value specified by the method directly 
#
# 
# @param pRoot TreeNode class  
# @return TreeNode class 
#

class Solution:
    def Mirror(self , pRoot: TreeNode) -> TreeNode:
        # write code here
        if pRoot is None:
            return None 
        q = []
        q.append(pRoot)
        
        while len(q):
            for i in range(len(q)):
                node = q.pop()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
                # swap
                tmp = node.left
                node.left = node.right
                node.right = tmp
        return pRoot        
        

answer :

Look at recursion :
The problem solving steps :
1、 Special judgement : If pRoot It's empty , Returns an empty
2、 Exchange left and right subtrees
3、 hold pRoot Put the left subtree of Mirror Mirror in
4、 hold pRoot The right subtree of Mirror Mirror in
5、 Return root node root

class Solution:
    def Mirror(self , pRoot ):
        # write code here
        if not pRoot:
            return pRoot
        #  Left and right subtrees exchange 
        pRoot.left, pRoot.right = pRoot.right, pRoot.left
        #  Recursive left and right subtrees 
        self.Mirror(pRoot.left)
        self.Mirror(pRoot.right)
        
        return pRoot

I searched the Internet for a recursive solution :

To solve the problem of recursion is usually a three-step process , Namely :

First step , Define function function -> Flip the tree
The second step , Looking for recursive termination conditions -> It is already a leaf node or It's already empty
The second step , The equivalent relation of recursive function -> Flip node The left and right subtrees of

原网站

版权声明
本文为[strawberry47]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070814305714.html