LeetCode 116 Populating Next Right Pointers in Each Node 解題報告

Populating Next Right Pointers in Each Node
Total Accepted: 44163 Total Submissions: 122231

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

/*
*本題是將一顆完美二叉樹每一層用一個next指針連接起來,並且最右側的節點指向NULL。我的思路是,先用循環把右側的所有next指針設爲NULL,然後使用兩個指針,一個表示當前節點,另一個表示指向當前節點的前一個節點
然後按層,一層一層的把next指針都填充完畢。
一開始prev指向1,cur指向2。我們填充next指針的代碼放入一個循環中,分爲3種情況判斷
1:當cur指針是prev的左孩子時,這個時候只需將cur->next 指向prev->right即可。然後使用cur=cur->next把cur指針移向下一個節點。
2:當cur指針是右孩子,而且cur->next不爲NULL時,這個時候就是cur是prev的右孩子,但是不在最右側。這種情況只需把cur->next指向prev->next->left就可以了。然後把cur和prev都向next移動,指向下一個節點
3:其他情況也就是cur是最右側的節點,這時候需要判斷cur是否爲最後一個節點,如果是的話就退出循環,如果不是,則將cur和prev都指向下一層的第一個節點。
我們使用了cnt表示當前是第幾層,每執行到這個判斷代碼段的時候,我們把cnt自增,表示到下一層去。通過cnt的大小我們就可以通過循環找到下一層的第一個節點
*/

/**
 * 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)
        {
            return;
        }
        TreeLinkNode *cur = root;
        TreeLinkNode *prev = root;
        int cnt = 0;
        while(cur)
        {
            cur->next = NULL;
            cur = cur->right;
        }
        if(root->left)
            cur = root->left;
        else
            return;
        while(true)
        {
            if(cur == prev->left)
            {
                cur->next = prev->right;
                cur = cur->next;
            }
            else if(cur == prev->right && prev->next != NULL)
            {
                cur->next = prev->next->left;
                cur = cur->next;
                prev = prev->next;
            }
            else
            {
                if(cur->left == NULL)
                    break;
                else
                {
                    ++cnt;
                    prev = root;
                    for(int i = 0; i < cnt; ++i)
                        prev = prev->left;
                    cur = prev->left;
                }
            }
        }
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章