二叉树的镜像

tech2024-03-23  71

题目

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

分析

代码实现

class TreeNode{ int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } /** 操作给定的二叉树, 将其变换为源二叉树的镜像。 */ public class Solution { public static void main(String[] args) { TreeNode root = new TreeNode(4); TreeNode node1 = new TreeNode(2); TreeNode node2 = new TreeNode(7); TreeNode node3 = new TreeNode(1); TreeNode node4 = new TreeNode(3); TreeNode node5 = new TreeNode(6); TreeNode node6 = new TreeNode(9); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node2.left = node5; node2.right = node6; System.out.println(); Mirror(root); System.out.println(); } public TreeNode mirrorTree(TreeNode root) { if (root == null){ return null; } root.left = mirrorTree(root.right); root.right = mirrorTree(root.left); return root; } } public class Solution { public static void main(String[] args) { TreeNode root = new TreeNode(4); TreeNode node1 = new TreeNode(2); TreeNode node2 = new TreeNode(7); TreeNode node3 = new TreeNode(1); TreeNode node4 = new TreeNode(3); TreeNode node5 = new TreeNode(6); TreeNode node6 = new TreeNode(9); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node2.left = node5; node2.right = node6; System.out.println(); Mirror(root); System.out.println(); } public static void Mirror(TreeNode root) { if (root == null) { return; } //进行左右子树的交换 TreeNode temp;//用于交换的中间量 if (root.right != null || root.left != null) {//交换左右子树 temp = root.left; root.left = root.right; root.right = temp; } Mirror(root.left);//左递归 Mirror(root.right);//右递归 } }
最新回复(0)