class TreeNode {int val;TreeNode left, right;TreeNode(int val) {this.val = val;left = right = null;}
}public class BinaryTree {TreeNode root;// 递归翻转二叉树public TreeNode invertTree(TreeNode root) {if (root == null) {return null;}// 递归翻转左子树和右子树TreeNode left = invertTree(root.left);TreeNode right = invertTree(root.right);// 交换左右子树root.left = right;root.right = left;return root;}// 测试示例public static void main(String[] args) {BinaryTree tree = new BinaryTree();tree.root = new TreeNode(1);tree.root.left = new TreeNode(2);tree.root.right = new TreeNode(3);tree.root.left.left = new TreeNode(4);tree.root.left.right = new TreeNode(5);System.out.println("原始二叉树:");tree.printTree(tree.root);// 翻转二叉树tree.root = tree.invertTree(tree.root);System.out.println("\n翻转后的二叉树:");tree.printTree(tree.root);}// 打印二叉树(中序遍历)void printTree(TreeNode node) {if (node == null) {return;}printTree(node.left);System.out.print(node.val + " ");printTree(node.right);}
}
代码定义了一个简单的二叉树节点类 TreeNode
,以及一个二叉树类 BinaryTree
。其中 invertTree
方法用于翻转二叉树,通过递归的方式对每个节点进行左右子树的翻转。在 main
方法中,创建了一个简单的二叉树,并进行了翻转操作,最后打印出翻转后的二叉树结果。