Sword refers to offer to brush questions-GZ18-the mirror image of the binary tree

Insert picture description here
Problem-solving idea: swap the nodes of the left and right subtrees, and then call the method recursively.

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    
    
    public void Mirror(TreeNode root) {
    
    
        if(root==null){
    
    
            return;
        }
        //前序遍历每个节点的非叶子节点,交换它的两个子节点,最终得到该二叉树的镜像
        TreeNode temp = null;
        temp = root.left;
        root.left = root.right;
        root.right = temp;
        //左右子树用递归自己处理就ok了
        Mirror(root.left);
        Mirror(root.right);
    }
}

Guess you like

Origin blog.csdn.net/weixin_42118981/article/details/112913013