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


    需求分析

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

    如图

    实现代码:

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

    1. /**
    2. * @author CC
    3. * @version 1.0
    4. * @since2023/10/13
    5. */
    6. public class BinaryTree {
    7. //添加左节点
    8. public static TreeNode leftIn(TreeNode rootNode, int val) {
    9. TreeNode newNode = new TreeNode(val);
    10. rootNode.left = newNode;
    11. return newNode;
    12. }
    13. //添加右节点
    14. public static TreeNode rightIn(TreeNode rootNode, int val) {
    15. TreeNode newNode = new TreeNode(val);
    16. rootNode.right = newNode;
    17. return newNode;
    18. }
    19. //层序遍历
    20. public static void leverOrder(TreeNode root) {
    21. if (root == null) {
    22. return;
    23. }
    24. Queue queue = new LinkedList();
    25. queue.offer(root);
    26. while (true) {
    27. TreeNode curr = queue.poll();
    28. if (curr == null) {
    29. return;
    30. }
    31. System.out.print(curr.val);
    32. if (curr.left != null) {
    33. queue.offer(curr.left);
    34. }
    35. if (curr.right != null) {
    36. queue.offer(curr.right);
    37. }
    38. }
    39. }
    40. //二叉树节点类
    41. public static class TreeNode {
    42. private int val;
    43. private TreeNode left;
    44. private TreeNode right;
    45. TreeNode(int val) {
    46. this.val = val;
    47. }
    48. }
    49. }

    实现二叉树的镜像方法:

    1. public static TreeNode mirror(TreeNode root) {
    2. if (root == null) {
    3. return null;
    4. }
    5. Stack stack = new Stack<>();
    6. stack.push(root);
    7. while (!stack.isEmpty()) {
    8. TreeNode node = stack.pop();
    9. if (node.left != null) {
    10. stack.push(node.left);
    11. }
    12. if (node.right != null) {
    13. stack.push(node.right);
    14. }
    15. TreeNode temp = node.left;
    16. node.left = node.right;
    17. node.right = temp;
    18. }
    19. return root;
    20. }

    测试:

    1. public static void main(String[] args) {
    2. TreeNode root = new TreeNode(1);
    3. TreeNode node2 = leftIn(root, 2);
    4. TreeNode node3 = rightIn(root, 3);
    5. TreeNode node4 = leftIn(node2, 4);
    6. TreeNode node5 = rightIn(node2, 5);
    7. TreeNode node6 = leftIn(node3, 6);
    8. TreeNode node7 = rightIn(node3, 7);
    9. //镜像前先层序遍历
    10. System.out.print("镜像前先层序遍历:");
    11. leverOrder(root);
    12. System.out.println();
    13. //执行镜像方法
    14. mirror(root);
    15. //镜像后层序遍历
    16. System.out.print("镜像后先层序遍历:");
    17. leverOrder(root);
    18. }

    测试结果:

  • 相关阅读:
    【游戏建模全流程】使用ZBrush制作龙模型
    3.事务篇【mysql高级】
    Socks5代理IP在跨境电商与网络游戏中的网络安全应用
    input 只能输入正数并且只能保留3位小数且开头不能为0,并且表单多字段使用
    如何更改代理ip,变更代理ip怎么实现?
    NFT营销如何赋能品牌破圈增长?
    ArcGIS笔记9_数据源缺少空间参考信息?如何定义坐标系?
    WebDAV之葫芦儿·派盘+i简记
    RetroArch 接入两个同款手柄只能识别到一个导致无法双打的问题
    SpringBoot的初步认识
  • 原文地址:https://blog.csdn.net/c1390527393/article/details/133810143