简繁EN

LeetCodeNo. 084

【LeetCode with Python】 116. Populating Next Right Pointers in Each Node

目錄

題目

原題頁面:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
題目型別:Tree, Depth-first SearchTwo Pointers
難度評價:Medium
類似題目:(H) Populating Next Right Pointers in Each II Node, (M) Binary Tree Right Side View

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

分析

題目保證是滿二叉樹(所有葉子在同一層,每個父結點都有左右兩個孩子),而且要求只能用常量額外空間。用層次遍歷(參考Binary Tree Level Order Traversal這道題的程式碼)把每一層的結點存進列表,再串上next指標,結果是對的,但列表裡要放一整層的結點,最底層的結點差不多佔了一半,額外空間是O(n)。
連第k+1層的時候,第k層的next已經在上一輪連好了。從最左邊的結點(程式碼裡的level_head)開始順著next往右,就能訪問到第k層的所有結點。
對第k層的每個結點cur,cur.left.next = cur.right,把同一個父結點的兩個孩子連起來;cur.next不為空時,cur.right.next = cur.next.left,這樣相鄰兩個父結點之間的那一對孩子也連上了。
一層走完,level_head下移到level_head.left,也就是下一層最左邊的結點,直到level_head沒有左孩子(葉子層)為止。根結點和每一層最右邊結點的next不用管,它們本來就是NULL。
時間複雜度是O(n),額外空間只有level_head和cur兩個指標,是O(1)。
這道題的衍生版本Populating Next Right Pointers in Each Node II裡的樹可以是任意結構,結點可能缺孩子,程式碼不能直接拿過去用,那道題的做法看那篇。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Definition for a  binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None

class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
if None == root:
return [ ]
level_head = root
while None != level_head.left:
cur = level_head
while None != cur:
cur.left.next = cur.right
if None != cur.next:
cur.right.next = cur.next.left
cur = cur.next
level_head = level_head.left

本文地址:https://xnerv.wang/zh-tw/leetcode-populating-next-right-pointers-in-each-node/