剑指offer 反转二叉树

bfs

class Solution {
public:
    void swap_tn(TreeNode*& a, TreeNode*& b){
        auto temp = a;
        a = b;
        b = temp;
    }
    void Mirror(TreeNode *pRoot) {
        if(pRoot == nullptr) return;
        queue<TreeNode*> q;
        q.push(pRoot);
        while(!q.empty()){
            auto node = q.front();
            q.pop();
            swap_tn(node->left, node->right);
            if(node->left != nullptr) q.push(node->left);
            if(node->right != nullptr) q.push(node->right);
        }
    }
};

dfs

class Solution {
public:
    void swap_tn(TreeNode*& a, TreeNode*& b){
        auto temp = a;
        a = b;
        b = temp;
    }
    void Mirror(TreeNode *pRoot) {
        if(pRoot == nullptr) return;
        swap_tn(pRoot->left, pRoot->right);
        Mirror(pRoot->left);
        Mirror(pRoot->right);
        }
};
posted @ 2018-08-30 11:30  一条图图犬  阅读(85)  评论(0编辑  收藏  举报