[LeetCode]Populating Next Right Pointers in Each Node

題目鏈接:Populating Next Right Pointers in Each Node

題目內容:

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

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

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL

題目解法:

這道題本來只是一道簡單的計層BFS題目,但是有一個對於常數額外空間複雜度的要求,因此不能使用傳統的隊列BFS,可以只定義一個變量cur,根據樹的性質來完成BFS,具體方法如下:

首先初始化cur爲root,cur的每次動作是從左到右的,通過cur = cur->next實現;當cur->next==NULL時,讓cur沿着root的左子樹往下走,也就是root = root->left; cur = root;當我們設置next時,實際上我們是設置的下一層的next,因此當訪問當前層的next時,已經被設置過。

下面舉個例子,如上面一棵完全二叉樹,假設現在cur=2,在第一層我們已經設置了2的next爲3,因此在本層通過cur->left->next=cur->right設置4->5,因爲cur->next!=NULL,因此我們設置cur->right->next=cur->next->left,也就是2的右子樹5指向3的左子樹6,然後cur=3,繼續操作。

代碼如下:

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(root == NULL) return;
        TreeLinkNode *cur;
        while(root->left != NULL){
            cur = root;
            while(cur != NULL){
                cur->left->next = cur->right;
                if(cur->next != NULL)
                    cur->right->next = cur->next->left;
                cur = cur->next;
            }
            root = root->left;
        }
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章