学习笔记-翻转二叉树-从遍历到翻转


前言

翻转二叉树是一种简单的二叉树问题,下面我们分别从递归和迭代的角度解决它。
可以完成leetcode上的
226.翻转二叉树


一、递归

前序遍历

依据 中-左-右 的顺序,我们先从根节点开始,交换left和right,在用递归的方法分别翻转左子树和右子树,完成整个二叉树的翻转。
代码如下:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL) return NULL;
        // TreeNode* tem =root->left;
        // root->left =root->right;
        // root->right= tem;
        swap(root->left,root->right);//直接使用函数
        invertTree(root->left);
        invertTree (root->right);
        return root;
    }
};

层序遍历

按照二叉树的深度进行遍历,对每一个节点的left和right指针进行交换,直到叶节点再返回,递归交换所有节点的左右指针,完成对二叉树的翻转。

class Solution {
public:
    void order(TreeNode*cur ,int depth){
            if(cur==NULL) return ;
            swap(cur->left,cur->right);
            order(cur->left,depth+1);
            order(cur->right,depth+1);
    }
    TreeNode* invertTree(TreeNode* root) {
        int depth =0;
        order(root,depth);
        return root;
    }
};

二、迭代

能递归就一定可以迭代,我们再使用迭代法尝试完成此题。

前序遍历

与遍历不同的是,当弹出栈顶后,我们将它的左右指针交换位置,再将指针分别存入栈中,依次完成所有指针的交换,进而翻转二叉树。
代码如下:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL) return root;
        stack<TreeNode*> st;
        st.emplace(root);
        while(!st.empty()){
            TreeNode*cur=st.top();
            st.pop();
            swap(cur->left,cur->right);
            if(cur->right) st.emplace(cur->right);
            if(cur->left) st.emplace(cur->left);
        }
        return root;
    }
};

层序遍历

与前序一样,在弹出队列首元素后它的左右指针交换位置。
代码如下:

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==NULL)  return root;
        queue <TreeNode*> que;
        que.emplace(root);
        while(!que.empty()){
            int size=que.size();
            for(int i=0;i<size;i++){
                TreeNode*cur=que.front();
                que.pop();
                swap(cur->left,cur->right);
                if(cur->left) que.emplace(cur->left);
                if(cur->right) que.emplace(cur->right);
            }
        }
        return root;
    }
};

运行结果

在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值