The sword refers to Offer-question 27 (Java Edition): Mirror image of binary tree

Reference from: "Sword Pointing Offer - Famous Enterprise Interviewer Talking About Typical Programming Questions"

Question : Mirroring of a binary tree
Please complete a function that takes a binary tree as input, and the function outputs its mirror image (with left and right child nodes swapped).
E.g:

//            10
//         /      \
//        6        14
//       /\        /\
//      4  8     12  16

The mirror is:

//            10
//         /      \
//       14        6
//       /\        /\
//      16 12     8  4

Main idea : The mirror image of a binary tree can be imagined as centering on the parent node and exchanging the positions of the left and right child nodes. Therefore, the left and right children of each node need to be swapped recursively.

Key Points : Recursion, Definition of Binary Tree Mirroring

Time complexity : O(n)

public class MirrorTree
{
    public static void main(String[] args)
    {
//            10
//         /      \
//        6        14
//       /\        /\
//      4  8     12  16
        TreeNode root = TreeNode.generateBinaryTree();
        mirrorNode(root);        
    }

    private static TreeNode mirrorNode(TreeNode root)
    {
        if (root == null) return null;
        TreeNode leftNode = root.left;
        TreeNode rightNode = root.right;
        //递归交换左右子节点
        root.left = mirrorNode(rightNode);
        root.right = mirrorNode(leftNode);
        return root;
    }
}

public class TreeNode
{
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x)
    {
        val = x;
    }

//            10
//         /      \
//        6        14
//       /\        /\
//      4  8     12  16
    /**
     * 生成二叉搜索树
     * @return
     */
    public static TreeNode generateBinaryTree()
    {
        TreeNode root = new TreeNode(10);
        TreeNode node6 = new TreeNode(6);
        TreeNode node14 = new TreeNode(14);
        TreeNode node4 = new TreeNode(4);
        TreeNode node8 = new TreeNode(8);
        TreeNode node12 = new TreeNode(12);
        TreeNode node16 = new TreeNode(16);
        connectNode(root, node6, node14);
        connectNode(node6, node4, node8);
        connectNode(node14, node12, node16);
        return root;
    }

    private static void connectNode(TreeNode root, TreeNode left, TreeNode right)
    {
        root.left = left;
        root.right = right;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325896166&siteId=291194637