题解 | #翻转牛群结构#
翻转牛群结构
https://www.nowcoder.com/practice/f17e1aa5329f492f9107cbe303222ad6
一、知识点:
二叉树、递归
二、文字分析:
递归的方法来翻转二叉树。具体来说,我们首先交换当前节点的左子节点和右子节点,然后递归地翻转左子树和右子树。
这个程序的时间复杂度和空间复杂度都是 O(N),其中 N 是二叉树中节点的数量。
三、编程语言:
java
四、正确代码:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
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;
}
}

