java二叉树反转怎么写
时间: 2023-03-15 19:54:23 浏览: 112
二叉树反转是指将一棵二叉树的左右子树互换,可以通过递归的方式实现。
以下是Java代码示例:
```java
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
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;
}
```
在上述代码中,我们首先判断当前节点是否为null,如果是,则直接返回null。否则,我们将左子树和右子树分别反转,然后将当前节点的左子树指向反转后的右子树,右子树指向反转后的左子树。最后,返回当前节点。这个过程是递归进行的,直到所有节点都被反转。
相关问题
java 写一个二叉树反转
二叉树反转,即将每个节点的左右子树交换位置。可以使用递归实现:
```java
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class BinaryTreeInversion {
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;
}
}
```
在 main 方法中可以测试一下:
```java
public static void main(String[] args) {
/*
* 4
* / \
* 2 7
* / \ / \
* 1 3 6 9
*/
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
TreeNode node9 = new TreeNode(9);
node4.left = node2;
node4.right = node7;
node2.left = node1;
node2.right = node3;
node7.left = node6;
node7.right = node9;
BinaryTreeInversion inversion = new BinaryTreeInversion();
TreeNode invertedTree = inversion.invertTree(node4);
// 输出反转后的二叉树的前序遍历结果
printPreOrder(invertedTree);
}
private static void printPreOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
printPreOrder(root.left);
printPreOrder(root.right);
}
```
输出结果为:`4 7 9 6 2 3 1`,说明二叉树已经被反转了。
java实现反转二叉树
要在Java中实现反转二叉树,可以使用递归或非递归的方法。以下是两种实现方式:
1. 递归实现:
```java
public TreeNode invertNode(TreeNode root) {
if(root == null) return root;
TreeNode temp = root.left;
root.left = invertNode(root.right);
root.right = invertNode(temp);
return root;
}
```
2. 非递归实现:
```java
public TreeNode invertNode(TreeNode root) {
if(root == null) return null;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()) {
TreeNode current = queue.poll();
TreeNode temp = current.left;
current.left = current.right;
current.right = temp;
if(current.left != null) queue.add(current.left);
if(current.right != null) queue.add(current.right);
}
return root;
}
```
以上是两种在Java中实现反转二叉树的方法,你可以根据需要选择其中一种来使用。<span class="em">1</span><span class="em">2</span>
阅读全文