剑指offer67题-No18.二叉树镜像

递归

class Solution {
public:
    TreeNode* Mirror(TreeNode* pRoot) {
        //空树返回
        if(pRoot == NULL) 
            return NULL;
        //先递归子树
        TreeNode* left = Mirror(pRoot->left);  
        TreeNode* right = Mirror(pRoot->right);
        //交换
        pRoot->left = right; 
        pRoot->right = left;
        return pRoot;
    }
};

辅助队列层次遍历

class Solution {
public:
    TreeNode* Mirror(TreeNode* pRoot) {
        if(pRoot == nullptr) return nullptr;
        
        auto *newT = new TreeNode(pRoot->val);
        std::queue<TreeNode*> q;
        q.push(pRoot);
         
        while(!q.empty()){
            TreeNode* cur = q.front();
            q.pop();
            if(cur != nullptr){
                q.push(cur->left);
                q.push(cur->right);
                // 节点交换
                TreeNode*  tmp = cur->left;
                cur->left = cur->right;
                cur->right = tmp;
            }
        }
        return pRoot;

    }
};
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇