题解 | #翻转牛群结构#
翻转牛群结构
https://www.nowcoder.com/practice/f17e1aa5329f492f9107cbe303222ad6?tpId=354&tqId=10591478&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D354
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 left = root.left;
root.left = root.right;
root.right = left;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
知识点:
- 二叉树基本概念:了解二叉树的定义和基本特点,包括根节点、左子树、右子树等。
- 递归:理解递归的概念,以及如何利用递归来实现二叉树的翻转。
题目解答方法:
要翻转二叉树,可以通过递归地交换每个节点的左子树和右子树来实现。具体步骤如下:
- 编写一个递归函数 invertTree,该函数接受一个二叉树的根节点作为参数。
- 如果根节点为空,直接返回 null。
- 交换根节点的左子树和右子树。
- 递归地对根节点的左子树和右子树调用 invertTree。
