[Swipe the question bank] Sword refers to Offer_ programming questions, the mirror image of the binary tree.

Title description

Operate the given binary tree and transform it into a mirror image of the source binary tree.

Enter description:

Time limit: 1 second Space limit: 32768K Heat index: 316600

Knowledge points of this question:  tree

To understand the structure of the tree, you can view the previous notes:

Common methods for understanding trees and binary trees ( you can use the complete code at the end of this article to write and test the topic )

 

Problem analysis:

It is very simple, that is, mirror output of a tree, that is, the left subtree of a node becomes the right subtree, and its right subtree becomes the left subtree.

This requires traversing each node and swapping its left and right subtrees.

 

Recursive realization, traversing each node, you can think of recursive thinking ( remember to add the end condition )

function Mirror(root)
{
    //结束条件
    if(root == null) {
        return ;
    }
    //声明一个变量来存储右结点
    var temp = root.right;
    //将右结点等于左结点
    root.right = root.left;
    //将左结点等于右结点
    root.left = temp;

    //如果存在右结点,继续遍历
    Mirror(root.right);
    //如果存在左结点,继续遍历
    Mirror(root.left);
}

 

Recursive Deconstruction Implementation

function Mirror(root)
{
    //结束条件
    if(root == null) return ;
    //解构交换
    [root.right, root.left] = [root.left, root.right];
    Mirror(root.right);
    Mirror(root.left);
}

 

Guess you like

Origin blog.csdn.net/weixin_42339197/article/details/100148251