【LeetCode每日一题】——226.翻转二叉树

一【题目类别】

  • 深度优先搜索

二【题目难度】

  • 简单

三【题目编号】

  • 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 是树的结点个数

九【代码实现】

  1. 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;
    }

}
  1. 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;
}

/*主函数省略*/

十【提交结果】

  1. Java语言版
    在这里插入图片描述

  2. C语言版
    在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IronmanJay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值