sundeepblue
3/26/2014 - 2:10 AM

mirror a binary tree

mirror a binary tree

struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v) : val(v) {}
};

// solution 1: create a copy of mirrored binary tree
// top-down way
TreeNode *mirror(TreeNode *root) {
    if(!root) return NULL;
    TreeNode *r = new TreeNode(root->val);
    r->left = mirror(root->right);
    r->right = mirror(root->left);
    return r;
}

// solution 2: in-place mirror, exchange pointers
// bottom-up way
void mirror(TreeNode *&root) {    // should be *& ?
    if(!root) return;
    mirror(root->left);
    mirror(root->right);
    TreeNode *tmp = root->left;
    root->left = root->right;
    root->right = tmp;
}