翻转二叉树-力扣

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

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;
    }
};
相关推荐
呆呆的小鳄鱼24 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香24 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely25 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_071225 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_41 分钟前
cf1925B&C
数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
Wendy14419 小时前
【线性回归(最小二乘法MSE)】——机器学习
算法·机器学习·线性回归
拾光拾趣录9 小时前
括号生成算法
前端·算法
渣呵10 小时前
求不重叠区间总和最大值
算法
拾光拾趣录10 小时前
链表合并:双指针与递归
前端·javascript·算法