【数据结构与算法】二叉树的镜像实现

需求分析

        将所有节点的左子树与右子树交换,以达到交换前与交换后成为镜像的效果。

如图【数据结构与算法】二叉树的镜像实现_第1张图片

实现代码:

先准备一个二叉树具有节点类,添加左右子节点的方法和层序遍历方法。

/**
 * @author CC
 * @version 1.0
 * @since2023/10/13
 */
public class BinaryTree {
    

    //添加左节点
    public static TreeNode leftIn(TreeNode rootNode, int val) {
        TreeNode newNode = new TreeNode(val);
        rootNode.left = newNode;
        return newNode;
    }

    //添加右节点
    public static TreeNode rightIn(TreeNode rootNode, int val) {
        TreeNode newNode = new TreeNode(val);
        rootNode.right = newNode;
        return newNode;
    }


    //层序遍历
    public static void leverOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue queue = new LinkedList();
        queue.offer(root);

        while (true) {
            TreeNode curr = queue.poll();
            if (curr == null) {
                return;
            }
            System.out.print(curr.val);
            if (curr.left != null) {
                queue.offer(curr.left);
            }
            if (curr.right != null) {
                queue.offer(curr.right);
            }
        }

    }


    //二叉树节点类
    public static class TreeNode {
        private int val;
        private TreeNode left;
        private TreeNode right;

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

实现二叉树的镜像方法:

 public static TreeNode mirror(TreeNode root) {
        if (root == null) {
            return null;
        }

        Stack stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();

            if (node.left != null) {
                stack.push(node.left);
            }

            if (node.right != null) {
                stack.push(node.right);
            }

            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }
        return root;
    }

测试:

public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node2 = leftIn(root, 2);
        TreeNode node3 = rightIn(root, 3);

        TreeNode node4 = leftIn(node2, 4);
        TreeNode node5 = rightIn(node2, 5);
        TreeNode node6 = leftIn(node3, 6);
        TreeNode node7 = rightIn(node3, 7);

        //镜像前先层序遍历
        System.out.print("镜像前先层序遍历:");
        leverOrder(root);
        System.out.println();

        //执行镜像方法
        mirror(root);
       
        //镜像后层序遍历
        System.out.print("镜像后先层序遍历:");
        leverOrder(root);

    }

测试结果:

【数据结构与算法】二叉树的镜像实现_第2张图片

你可能感兴趣的:(java,算法,开发语言)