[Tree] Mirror of Binary Tree

Title description

Operate the given binary tree and transform it into a mirror image of the source binary tree.
For example: Source Binary Tree 8/ 6 10/ \ / 5 7 9 11 Mirror Binary Tree 8/ 10 6/ \ / 11 9 7 5

Insert picture description here


The idea is very simple, just recursively traverse the tree, and then swap the left and right subtrees of each node.

import java.util.*;


public class Solution {
    
    
 
    public TreeNode Mirror(TreeNode pRoot) {
    
    
        // write code here
        if (pRoot != null) {
    
    
            TreeNode tmp = pRoot.left;
            pRoot.left = pRoot.right;
            pRoot.right = tmp;
            Mirror(pRoot.left);
            Mirror(pRoot.right);
        }
        return pRoot;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43486780/article/details/115047576