Niuke Net Brushing Questions-Mirror Image of Binary Tree

Problem Description

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

Input description:
Input a binary tree

Output description:
output the mirror image of the binary tree

Example

Example 1

enter
Insert picture description here

Output
Insert picture description here

Solutions

analysis

  • Realize the exchange of left and right subtrees through recursion, which can be bottom-up or top-down

method

  1. Bottom-up exchange via recursion

Code

public class Solution {
    
    
    public void Mirror(TreeNode root) {
    
    
        if (root == null) {
    
    
            return;
        }

        // 临时变量存储
        TreeNode left = root.left;
        TreeNode right = root.right;

        // 递归
        Mirror(left);
        Mirror(right);

        // 交换
        root.left = right;
        root.right = left;
    }
}

If you want to test, you can go directly to the link of Niuke.com to do the test

Mirror of Binary Tree

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/112845411