简繁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/leetcode-populating-next-right-pointers-in-each-node/