1. 程式人生 > >Leetcode 116:填充同一層的兄弟節點(超詳細的解法!!!)

Leetcode 116:填充同一層的兄弟節點(超詳細的解法!!!)

給定一個二叉樹

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

填充它的每個 next 指標,讓這個指標指向其下一個右側節點。如果找不到下一個右側節點,則將 next 指標設定為 NULL

初始狀態下,所有 next 指標都被設定為 NULL

說明:

  • 你只能使用額外常數空間。
  • 使用遞迴解題也符合要求,本題中遞迴程式佔用的棧空間不算做額外的空間複雜度。
  • 你可以假設它是一個完美二叉樹(即所有葉子節點都在同一層,每個父節點都有兩個子節點)。

示例:

給定完美二叉樹,

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

呼叫你的函式後,該完美二叉樹變為:

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

解題思路

首先想到的解法是通過層序遍歷,可以參考這篇Leetcode 102:二叉樹的層次遍歷(最詳細解決方案!!!)

我們可以現將rootNone加入佇列,

queue: root None

然後將隊首元素彈出,首先判斷一下左右孩子

是不是空,將非空的孩子加入佇列。

queue: None root.left root.right

此時我們發現隊首元素為None,但是佇列不為空,所以我們再加入一個None

queue: root.left root.right None

通過上述這種操作,我們就可以將每行的結尾確定,然後我們只要判斷當前出隊元素cur是不是空,如果不是的話,我們就將之前出隊的元素pre.next=cur

class Solution:
    # @param root, a tree link node
    # @return nothing
    def connect
(self, root): if not root: return q = [root, None] while q: node = q.pop(0) if node: node.next = q[0] if node.left: q.append(node.left) if node.right: q.append(node.right) else: if q: q.append(None)

這個問題可以不用佇列來做。我們可以將每一行的第一個元素當成起點,假設我們考慮當前元素cur

如果cur.left不為空,那麼我們令cur.left.next=cur.right

如果cur.rightcur.next都不為空,那麼我們令cur.right.next = cur.next.left。然後cur=cur.next,進行下一波。

程式碼如下。

class Solution:
    # @param root, a tree link node
    # @return nothing
    def connect(self, root):
        node = root
        while node:
            cur = node
            while cur:
                if cur.left:
                    cur.left.next = cur.right
                    
                if cur.right and cur.next:
                    cur.right.next = cur.next.left
                    
                cur = cur.next
            
            node = node.left

基於同樣的思路,我們可以快速寫出遞迴的方案。

class Solution:
    # @param root, a tree link node
    # @return nothing
    def connect(self, root):
        if not root:
            return 
        
        if root.left:
            root.left.next = root.right
            
        if root.right and root.next:
            root.right.next = root.next.left
            
        self.connect(root.left)
        self.connect(root.right)           

reference:

https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/37472/A-simple-accepted-solution

我將該問題的其他語言版本新增到了我的GitHub Leetcode

如有問題,希望大家指出!!!