简繁EN

LeetCodeNo. 085

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

目錄

題目

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

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

分析

和Populating Next Right Pointers in Each Node的區別是,這道題的樹不保證是滿二叉樹,結點可能缺孩子。題目同樣要求只能用常量額外空間。
那道題的寫法用cur.right.next = cur.next.left(cur是上一層當前的結點)去連相鄰的兩個孩子。這道題裡下一層挨著的兩個結點,它們的父結點在上一層可能隔著幾個沒有孩子的結點。題目樣例裡結點3就沒有左孩子,那段程式碼還要用cur.left.next = cur.right去連它的兩個孩子,到這裡就出錯了。
思路還是一層一層地連,從只有根結點、不用連的第一層開始。上一層的next已經連好了,沿著它從左往右走,每走到一個結點,就把它的左孩子、右孩子(有的話)依次接到下一層連結串列的末尾。
我用一個啞結點dummy當下一層連結串列的頭,tail指向當前的末尾,這樣第一個孩子也只是接到tail後面。
走完上一層以後,把cur設成dummy.next。每一層開始前要先把dummy.next清成None,不然到了最底下一層,dummy.next還留著上一輪的值,cur變不成None,一層接一層的迴圈就停不下來。連結串列末尾那個結點的next不用管,初始就是NULL。
時間O(n),每個結點走到一次,根以外的結點還會被接進連結串列一次。額外空間只有dummy、tail、cur這三個變數,是O(1)。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 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 [ ]
dummy = TreeNode(-1)
cur = root
while None != cur:
dummy.next = None
tail = dummy
while None != cur:
if None != cur.left:
tail.next = cur.left
tail = tail.next
if None != cur.right:
tail.next = cur.right
tail = tail.next
cur = cur.next
cur = dummy.next

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