题解 | #翻转牛群结构#
翻转牛群结构
https://www.nowcoder.com/practice/f17e1aa5329f492f9107cbe303222ad6
知识点
树,递归
解题思路
我们直接递归让树的左子树赋值为树的右子树,右子树赋值为左子树。
注意如果知识在树本身上进行修改,那么需要提前将树的右子树进行保存,因为当右子树被赋值为左子树后,树发生了变化,需要保存临时变量。
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 { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return TreeNode类 */ public TreeNode invertTree (TreeNode root) { // write code here if(root == null) return null; TreeNode temp = root.right; root.right = invertTree(root.left); root.left = invertTree(temp); return root; } }