填充每個節點的下一個右側節點指針

我的方法,使用顏色層次遍歷法,依次填next:

"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        white = 1
        gray = 0
        level = 0
        stack = [(white, root, level),]
        res = []
        
        if root is None:return
        
        while stack:
            color, root, level = stack.pop()
            if root is None: continue
            if color:
                stack.append((white, root.right, level+1))
                stack.append((white, root.left, level+1))
                stack.append((gray, root, level))
            else:
                if res.__len__() < level + 1:
                    res.append([root])
                elif res[level].__len__() == 2 ** (level) - 1:
                    res[level][0].next = root
                    root.next = None
                else:
                    res[level][0].next = root
                    res[level][0] = root
        return res[0][0]

遞歸法:

"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if root is None: #針對輸入爲[]這種特殊情況
            return root
        if root.left is None and root.next is None: #針對輸入爲[1]這種情況
            root.next = None
            return root
        if root.left is None: #不會讓程序訪問到最後一層,在倒數第二層就停了
            return root
        if root.next is None:
            root.left.next = root.right
            root.right.next = None
        else:
            root.left.next = root.right
            root.right.next = root.next.left
        
        self.connect(root.left)
        self.connect(root.right)

        return root

 

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