LeetCode C++ 226. Invert Binary Tree【Tree】简单

本文详细介绍了四种不同的二叉树翻转算法实现,包括先序遍历、中序遍历、后序遍历和层序遍历,并对比了它们的执行效率和内存消耗。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Invert a binary tree.

Example:
Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Trivia:
This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.

题意:翻转一棵二叉树。


思路1:先序遍历。代码如下:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return root;
        swap(root->left, root->right);
        root->left = invertTree(root->left);
        root->right = invertTree(root->right);
        return root;
    }
};

效率:

执行用时:4 ms, 在所有 C++ 提交中击败了60.36% 的用户
内存消耗:9.3 MB, 在所有 C++ 提交中击败了52.45% 的用户

思路2:中序遍历。代码如下:

class Solution {
public: 
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return root;
        invertTree(root->left); //递归找到左结点
        swap(root->left, root->right);
        invertTree(root->left); //此时左右结点已经交换
        return root;
    }
};

效率如下:

执行用时:4 ms, 在所有 C++ 提交中击败了60.36% 的用户
内存消耗:9.2 MB, 在所有 C++ 提交中击败了61.82% 的用户

思路3:后序遍历。代码如下:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (!root) return root;
        root->left = invertTree(root->left);
        root->right = invertTree(root->right);
        swap(root->left, root->right);
        return root;
    }
};

效率:

执行用时:4 ms, 在所有 C++ 提交中击败了60.36% 的用户
内存消耗:9.3 MB, 在所有 C++ 提交中击败了41.42% 的用户

思路4:层序遍历。代码如下:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if (root == nullptr) return root;
        queue<TreeNode*> q;
        q.push(root); 
        while (!q.empty()) {
            TreeNode *t = q.front(); q.pop();
            swap(t->left, t->right);
            if (t->left) q.push(t->left);
            if (t->right) q.push(t->right);
        }
        return root;
    } 
};

效率:

执行用时:0 ms, 在所有 C++ 提交中击败了100.00% 的用户
内存消耗:9.4 MB, 在所有 C++ 提交中击败了15.61% 的用户
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

memcpy0

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

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

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

打赏作者

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

抵扣说明:

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

余额充值