翻转二叉树-力扣

翻转二叉树,通过前序遍历的顺序,从根节点开始,将节点的左右子节点一次进行交换即可。

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == nullptr){
            return root;
        }
        TreeNode* temp = root->left;
        root->left = root->right;
        root->right = temp;

        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};

使用迭代的统一写法,前序遍历代码如下:

cpp 复制代码
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        stack<TreeNode*> st;
        if(root != nullptr){
            st.push(root);
        }
        while(!st.empty()){
            TreeNode* cur = st.top();
            st.pop();
            if(cur != nullptr){
                //st.pop();
                if(cur->right != nullptr) {
                    st.push(cur->right);
                }
                if(cur->left != nullptr) {
                    st.push(cur->left);
                }
                st.push(cur);
                st.push(nullptr);
            } else {
                //st.pop();
                TreeNode * cur = st.top();
                st.pop();
                swap(cur->left, cur->right);
            }
        }
        return root;
    }
};
相关推荐
前端小刘哥1 天前
赋能在线教育与企业培训:视频直播点播平台EasyDSS视频点播的核心技术与应用实践
算法
吗~喽1 天前
【LeetCode】四数之和
算法·leetcode·职场和发展
Net_Walke1 天前
【散列函数】哈希函数简介
算法·哈希算法
卿言卿语1 天前
CC1-二叉树的最小深度
java·数据结构·算法·leetcode·职场和发展
码流之上1 天前
【一看就会一写就废 指间算法】执行操作后的最大 MEX —— 同余、哈希表
算法·面试
仰泳的熊猫1 天前
LeetCode:889. 根据前序和后序遍历构造二叉树
数据结构·c++·算法
2025年一定要上岸1 天前
【日常学习】10-15 学习re
学习·算法·正则表达式
aramae1 天前
数据结构与算法(递归)
开发语言·经验分享·笔记·算法
小欣加油1 天前
leetcode 329 矩阵中的最长递增路径
c++·算法·leetcode·矩阵·深度优先·剪枝
Emilia486.1 天前
【Leetcode&nowcode&数据结构】单链表的应用(初阶)
c语言·数据结构·算法·leetcode