LeetCode 筆記 - 116. Populating Next Right Pointers in Each Node Posted on 2022-05-15題目在此 116. Populating Next Right Pointers in Each Node給定一個 Perfect Binary Tree,請為每一個 node 的 next 指向右邊 node解題思維只要把每個節點該做的都做一做,其實就完成了那因為是 Perfect Binary Tree,所以可以利用特性少做蠻多判斷的我們要做的事情就只有兩件事把左子節點的 next 指向右子節點把右子節點的 next 指向 root 的左子節點接著就每個 node 照這個邏輯做一次就完成了!程式碼1234567891011121314151617181920212223"""# 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: 'Optional[Node]') -> 'Optional[Node]': if not root or not root.left: return root root.left.next = root.right if root.next: root.right.next = root.next.left self.connect(root.left) self.connect(root.right) return root也許你也會想看看LeetCode 筆記 - 117. Populating Next Right Pointers in Each Node IILeetCode 筆記 - 199. Binary Tree Right Side ViewLeetCode 筆記 - 1641. Count Sorted Vowel Strings