Invert Binary Tree

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

遞歸算法:
1、交換根節點的左右子樹。
2、對左右子樹分別執行遞歸交換 。

代碼如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* invertTree(struct TreeNode* root) {
    if(NULL == root)    return root;
    struct TreeNode *lnode, *rnode;


    lnode = invertTree(root->right);
    rnode = invertTree(root->left);
    root->left = lnode;
    root->right = rnode;

    return root;
}

非遞歸算法:
1、交換根結點的左右子結點
2、交換第二層及以後各層每個結點的左右子結點,類似於二叉樹層次遍歷

代碼如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

struct QNode {
    struct TreeNode *tmp;
    struct QNode *next;
};

struct LinkQueue {
    struct QNode *front, *rear; 
};

void EnQueue(struct LinkQueue *Q, struct TreeNode *root)
{
    struct QNode *s = (struct QNode *)malloc(sizeof(struct QNode));
    s->tmp = root;
    s->next = NULL;
    Q->rear->next = s;
    Q->rear = s;
}

//帶頭結點的隊列,Q->front指針指向頭結點
void DeQueue(struct LinkQueue *Q)
{
    struct QNode *p = Q->front->next;
    Q->front->next = p->next;

    if(Q->rear == p)
        Q->rear = Q->front;
    free(p);
}

struct TreeNode* invertTree(struct TreeNode* root)
{
    struct LinkQueue *Q = (struct LinkQueue *)malloc(sizeof(struct LinkQueue));
    Q->front = (struct QNode *)malloc(sizeof(struct QNode)); 
    Q->rear = Q->front;

    if(NULL == root)
        return root;
    EnQueue(Q, root);
    while(Q->front != Q->rear)   //當隊列爲空時,Q->front == Q->rear
    {
        struct TreeNode *front = Q->front->next->tmp;
        DeQueue(Q);
        struct TreeNode *tmp = front->left;
        front->left = front->right;
        front->right = tmp;
        if(front->left)
            EnQueue(Q, front->left);
        if(front->right)
            EnQueue(Q, front->right);
    }
    return root;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章