[LeetCode] 116&117. Populating Next Right Pointers in Each Node I&II_Medium tag: BFS(Dont know why leetcode tag it as DFS...)

时间:2023-03-09 14:39:54
[LeetCode] 116&117. Populating Next Right Pointers in Each Node I&II_Medium  tag: BFS(Dont know why leetcode tag it as DFS...)

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.
  • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

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 这个题目因为是每一层之间的元素的关系, 所以很明显用BFS? 不知道为啥tag DFS, anyways, 我想的思路为, 利用每一层heig不一样, 然后设置一个pre, pre_h, 如果pre_h跟现在的heig相同, 那
表明是同一层, pre.next = node, 然后BFS即可. 12/03/2019 Update: 可以用Space:O(1), 设置start 和cur对每一层的来遍历,因为是perfect binary tree,所以如果有left child,肯定有right child。 1. Constraints
1) can be empty 2. Ideas BFS T: O(n) S: O(n)
按层遍历 T: O(n) S: O(1) 3. Code 1)
 class Solution:
def connect(self, root):
pre, pre_h, queue = None, -1, collections.deque([(root, 0)])
while queue:
node, heig = queue.popleft()
if node:
if pre_h == heig:
pre.next = node
pre, pre_h = node, heig
queue.append(node.left)
queue.append(node.right)

2) S: O(1)    for 116, perfect binary tree

if not root: return
head, start, cur = root, root, None
while start.left:
cur = start
while cur:
cur.left.next = cur.right
if cur.next:
cur.right.next = cur.next.left
cur = cur.next
start = start.left
return head

3) S: O(1)    for 117, general binary tree, 用dummy来记录每一层之前的点, cur分别是一层中当时的点, root则为已经有next的parent的那一层的cur node.

"""
# Definition for a Node.
class Node(object):
def __init__(self, val=0, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
dummy, head = Node(), root
cur = dummy
while root:
if root.left:
cur.next = root.left
cur = cur.next
if root.right:
cur.next = root.right
cur = cur.next
root = root.next
if not root:
root = dummy.next
cur = dummy
dummy.next = None
return head

4. Test cases

     1
/ \
2 3
/ \ \
4 5 7