示例:
输入:root = [4,2,7,1,3,6,9] 输出:[4,7,2,9,6,3,1]
import com.sun.source.tree.Tree;
import java.util.ArrayDeque;
import java.util.Queue;
//2021-2-25
//剑指offer 简单
//二叉树镜像
//Definition for a binary tree node.
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class Solution3 {
//通过数组创建二叉树
public static TreeNode createBT(int[] arr, int i) // 初始时,传入的i==0
{
TreeNode root = null; // 定义根节点
if (i >= arr.length) // i >= arr.length 时,表示已经到达了根节点
return null;
root = new TreeNode(arr[i]); // 根节点
root.left= createBT(arr, 2*i+1); // 递归建立左孩子结点
root.right = createBT(arr, 2*i+2); // 递归建立右孩子结点
return root;
}
//层序遍历
public void Visit(TreeNode t) {
Queue<TreeNode> q1 = new ArrayDeque<TreeNode>();
if (t == null)
return;
if (t != null) {
q1.add(t);
}
while (!q1.isEmpty()) {
TreeNode t1 = q1.poll();
if (t1.left != null)
q1.add(t1.left);
if (t1.right != null)
q1.add(t1.right);
System.out.print(t1.val + " ");
}
System.out.println();
}
//实现二叉树镜像的方法
public TreeNode mirrorTree(TreeNode root) {
if(root == null )
return root;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
mirrorTree(root.left);
mirrorTree(root.right);
return root;
}
public static void main(String args[]){
//Solution3 so3 = new Solution3();
int[] arr = {4,2,7,1,3,6,9}; //数组
Solution3 so3 = new Solution3();
TreeNode root =so3.createBT(arr,0); //根据数组构建二叉树
so3.Visit(root); //层序遍历二叉树
so3.mirrorTree(root); //二叉树镜像
so3.Visit(root); //输出二叉树镜像
}
}
mirrorTree是实现二叉树镜像的方法、其他的代码是为了辅助理解、以及验证。