226. 翻转二叉树

方法1:递归法

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

void swapTreeNodes(struct TreeNode* root) {
    if (root == NULL) {
        return;
    }
    struct TreeNode* tmpNode = root -> left;
    root -> left = root -> right;
    root -> right = tmpNode;
    swapTreeNodes(root -> left);
    swapTreeNodes(root -> right);
}

struct TreeNode* invertTree(struct TreeNode* root){
    if (root == NULL) {
        return NULL;
    }
    swapTreeNodes(root);
    return root;
}

方法2:非递归法,借助队列的力量

struct Queue {
    struct TreeNode dataList[100];
    int size;//0
    int front;//-1
    int rear;//-1
};

void push(struct Queue *queue, struct TreeNode item) {
    if (queue -> size > 100) {
        return;
    }
    int rear = (queue -> rear + 1) % 100;
    queue -> dataList[rear] = item;
    queue -> rear = rear;
    queue -> size ++;
}

struct TreeNode *pop(struct Queue *queue) {
    if (queue -> size == 0) {
        return NULL;
    }
    
    int front = (queue -> front + 1) % 100;
    queue -> size --;
    queue -> front = front;
    return &queue -> dataList[front];
}

int isEmptyQueue(struct Queue *queue) {
    if (queue -> size == 0) {
        return 1;
    }
    return 0;
}

struct TreeNode* invertTree(struct TreeNode* root){
    if (root == NULL) {
        return NULL;
    }
    
    struct Queue *queue = (struct Queue *)malloc(sizeof(struct Queue));
    push(queue, *root);
    
    while (isEmptyQueue(queue) != 1) {
        struct TreeNode *node = pop(queue);
        struct TreeNode *tmp = node -> left;
        node -> left = node ->right;
        node -> right = tmp;
        if (node -> left != NULL) {
            push(queue, *node -> left);
        }
        if (node -> right != NULL) {
            push(queue, *node -> right);
        }
    }
    
    return root;
}

你可能感兴趣的:(226. 翻转二叉树)