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 = []
输出:[]

解题思路


https://leetcode-cn.com/problems/invert-binary-tree/solution/shou-hua-tu-jie-san-chong-xie-fa-di-gui-liang-chon/(解释很好)

//递归
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(!root)return nullptr;
        swap(root->left,root->right);
        invertTree(root->left);
        invertTree(root->right);
        return root;
    }
};
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        //广度优先 层序遍历
        if(!root) return nullptr;
        queue<TreeNode*> q;
        TreeNode* tmp=new TreeNode(0);
        q.push(root);
        while(!q.empty()){
            tmp=q.front();
            q.pop();
            swap(tmp->left,tmp->right);
            if(tmp->left)q.push(tmp->left);
            if(tmp->right)q.push(tmp->right);
        }
        return root;
    }
};
posted @ 2022-03-28 10:53  vhuivwet  阅读(29)  评论(0编辑  收藏  举报