当前位置:网站首页>Mirror image of sword finger offer binary tree

Mirror image of sword finger offer binary tree

2022-06-24 23:34:00 ciwei24456

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

such as :
Source binary tree
 Insert picture description here
Mirror binary tree
 Insert picture description here
Their thinking :
According to the definition of binary tree image , Consider recursive traversal (dfs) Binary tree , Swap the left side of each node / The right child node , The image of binary tree can be generated .
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

Python Code implementation :

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
原网站

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