算法刷题之二叉树的镜像

采用递归的思想,将二叉树的左子节点和右子节点进行交换。

package tree;


public class TreeMirror {
    /**

     二叉树的镜像定义:源二叉树
     8
     /  \
     6   10
     / \  / \
     5  7 9 11

     镜像二叉树
     8
     /  \
     10   6
     / \  / \
     11 9 7  5

     */
    class TreeNode {
         int val = 0;
         TreeNode left = null;
         TreeNode right = null;
         public TreeNode(int val) {
            this.val = val;
         }
     }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(8);
        root.left = new TreeNode(6);
        root.right = new TreeNode(10);
        root.left.left = new TreeNode(5);
        root.left.right = new TreeNode(7);
        root.right.left = new TreeNode(9);
        root.right.right = new TreeNode(11);

        printTree(root);

        mirrorTree(root);

        System.out.println();

        printTree(root);
    }

    public static void mirrorTree(TreeNode root) {
        if(root!=null){
            TreeNode tmpNode = root.left;
            root.left = root.right;
            root.right = tmpNode;
            mirrorTree(root.left);
            mirrorTree(root.right);
        }
    }

    public static void printTree(TreeNode node){
        if(node!=null){
            System.out.print(node.val+" ");
            printTree(node.left);
            printTree(node.right);
        }else {
            System.out.print(" ");
        }
    }
}

 

你可能感兴趣的:(算法刷题)