一【题目类别】
- 深度优先搜索
二【题目难度】
- 简单
三【题目编号】
- 226.翻转二叉树
四【题目描述】
- 给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
五【题目示例】
-
示例 1:
- 输入:root = [4,2,7,1,3,6,9]
- 输出:[4,7,2,9,6,3,1]
-
示例 2:
- 输入:root = [2,1,3]
- 输出:[2,3,1]
-
示例 3:
- 输入:root = []
- 输出:[]
六【解题思路】
- 这道题目很经典也很简单,利用深度优先遍历的思想
- 首先交换左右子树
- 然后向左子树递归
- 然后向右子树递归
- 最后返回翻转后的二叉树根结点
七【题目提示】
- 树中节点数目范围在 [0, 100] 内
- -100 <= Node.val <= 100
八【时间频度】
- 时间复杂度: O ( n ) O(n) O(n),其中 n n n 是树的结点个数
- 空间复杂度: O ( l o g 2 N ) O(log_{2}N) O(log2N),其中 n n n 是树的结点个数
九【代码实现】
- Java语言版
package Tree;
public class p226_InvertBinaryTree {
int val;
p226_InvertBinaryTree left;
p226_InvertBinaryTree right;
public p226_InvertBinaryTree() {
}
public p226_InvertBinaryTree(int val) {
this.val = val;
}
public p226_InvertBinaryTree(int val, p226_InvertBinaryTree left, p226_InvertBinaryTree right) {
this.val = val;
this.left = left;
this.right = right;
}
public static void main(String[] args) {
p226_InvertBinaryTree root = new p226_InvertBinaryTree(2);
p226_InvertBinaryTree left = new p226_InvertBinaryTree(1);
p226_InvertBinaryTree right = new p226_InvertBinaryTree(3);
root.left = left;
root.right = right;
p226_InvertBinaryTree newRoot = invertTree(root);
preOrder(newRoot);
}
public static void preOrder(p226_InvertBinaryTree root) {
if (root != null) {
System.out.println(root.val);
preOrder(root.left);
preOrder(root.right);
}
}
public static p226_InvertBinaryTree invertTree(p226_InvertBinaryTree root) {
if (root == null) {
return null;
}
p226_InvertBinaryTree temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
- C语言版
#include<stdio.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* invertTree(struct TreeNode* root)
{
if (root == NULL)
{
return NULL;
}
struct TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
return root;
}
/*主函数省略*/
十【提交结果】
-
Java语言版
-
C语言版