Leetcode 117. Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?

Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/
2 3
/ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/
2 -> 3 -> NULL
/ \
4-> 5 -> 7 -> NULL

題意:116題的followup,二叉樹不在保證是一棵完整二叉樹,并且要求只用O(1)的空間復雜度。

思路:
非滿二叉樹用116題的寬度優先搜索的方法仍然能夠解決,但是空間復雜度是O(n)。
O(1)空間復雜度沒有想到合適的方法,查看了discuss的解法。
discuss排名最高的解法,思路是用三個指針cur、pre和head:cur指向當前層遍歷到的節點,根據cur的left和right,將下一層節點的next連接起來;pre指向下一層遍歷到的前一個節點,主要用于連接下一層當前節點和它的前一個節點;head用于記錄下一層的第一個節點,用于更新cur。

public void connect(TreeLinkNode root) {
    if (root == null) {
        return;
    }

    TreeLinkNode cur = root;
    TreeLinkNode head = null;
    TreeLinkNode pre = null;

    while (cur != null) {
        while (cur != null) {
            if (cur.left != null) {
                if (pre == null) {
                    head = cur.left;
                    pre = cur.left;
                } else {
                    pre.next = cur.left;
                    pre = pre.next;
                }
            }
            if (cur.right != null) {
                if (pre == null) {
                    head = cur.right;
                    pre = cur.right;
                } else {
                    pre.next = cur.right;
                    pre = pre.next;
                }
            }
            cur = cur.next;
        }

        cur = head;
        //bug 如果head不置為null,會導致死循環
        head = null;
        pre = null;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容