根据二叉树的根节点root,反转这棵二叉树,并返回其根节点。
总体思想是采用层序遍历《Java 一文详解二叉树的层序遍历》
【第一步】交换root的左右子节点
【第二步】交换节点7的左右子节点
【第三步】交换节点2的左右子节点
- package cn.msf.tree;
-
- import javax.xml.namespace.QName;
- import java.util.ArrayDeque;
- import java.util.ArrayList;
- import java.util.Deque;
- import java.util.List;
-
- import static cn.msf.tree.LevelTraversal.levelPrint;
-
- /**
- * @author : msf
- * @date : 2022/12/6
- */
- public class InvertTree {
- public static void main(String[] args) {
- TreeNode root = new TreeNode(1);
- TreeNode node1 = new TreeNode(2);
- TreeNode node2 = new TreeNode(3);
- TreeNode node3 = new TreeNode(4);
- TreeNode node4 = new TreeNode(5);
- TreeNode node5 = new TreeNode(6);
- TreeNode node6 = new TreeNode(7);
-
- root.left = node1;
- root.right = node2;
- node1.left = node3;
- node1.right = node4;
- node2.left = node5;
- node2.right = node6;
- System.out.println("反转前 二叉树的层序遍历结果");
- List
> arrayLists = levelPrint(root); - for (ArrayList
arrayList : arrayLists) { - System.out.println(arrayList);
- }
- InvertTree tree = new InvertTree();
- root = tree.invertTree(root);
- System.out.println("反转后 二叉树的层序遍历结果");
- arrayLists = levelPrint(root);
- for (ArrayList
arrayList : arrayLists) { - System.out.println(arrayList);
- }
- }
-
- public TreeNode invertTree(TreeNode root) {
- if (root == null) {
- return null;
- }
- Deque
queue = new ArrayDeque<>(); - queue.addLast(root);
- while (!queue.isEmpty()) {
- int size = queue.size();
- for (int i = 0; i < size; i++) {
- TreeNode node = queue.removeFirst();
- if (node.left != null) {
- queue.addLast(node.left);
- }
- if (node.right != null) {
- queue.addLast(node.right);
- }
- if(node.left != null || node.right !=null) {
- TreeNode temp = node.left;
- node.left = node.right;
- node.right = temp;
- }
- }
- }
- return root;
- }
- }
上述代码执行结果: