题目描述:给你一棵二叉树的根节点 ,翻转这棵二叉树,并返回其根节点。root。
获得更多?算法思路:代码文档,算法解析的私得。
运行效果
完整代码
/**
* 2 * @Author: LJJ
* 3 * @Date: 2023/8/16 13:18
* 4
*/
public class InvertBinaryTree {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
//递归交换左右子树
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
// 递归翻转左子树和右子树
invertTree(root.left);
invertTree(root.right);
return root;
}
public static void main(String[] args) {
InvertBinaryTree invertBinaryTree = new InvertBinaryTree();
// 构造二叉树
TreeNode root = new TreeNode(4);
root.left = new TreeNode(2);
root.right = new TreeNode(7);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(3);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(9);
System.out.print("翻转前的二叉树中序遍历结果 : ");
inorderTraversal(root);
// 翻转二叉树
TreeNode invertedRoot = invertBinaryTree.invertTree(root);
System.out.println(" ");
// 打印翻转后的二叉树中序遍历结果
System.out.print("翻转后的二叉树中序遍历结果 : ");
inorderTraversal(invertedRoot);
}
// 中序遍历二叉树
private static void inorderTraversal(TreeNode root) {
if (root == null) {
return;
}
inorderTraversal(root.left);
System.out.print(root.val + " ");
inorderTraversal(root.right);
}
}