Leetcode 117.填充每个节点的下一个右侧节点指针 II
1 题目描述(Leetcode题目链接)
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
进阶:
- 你只能使用常量级额外空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
提示:
- 树中的节点数小于 6000
- -100 <= node.val <= 100
2 题解
与116题类似,不过需要先递归右子树。
"""
# 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: 'Node') -> 'Node':
if not root:
return root
if root.left:
if root.right:
root.left.next = root.right
else:
node = root.next
while node:
if not node.left and not node.right:
node = node.next
continue
if node.left:
root.left.next = node.left
elif node.right:
root.left.next = node.right
break
if root.right:
node = root.next
while node:
if not node.left and not node.right:
node = node.next
continue
if node.left:
root.right.next = node.left
elif node.right:
root.right.next = node.right
break
self.connect(root.right)
self.connect(root.left)
return root
参考别人写的迭代方法,利用链表将下一层节点串起来。
"""
# 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: 'Node') -> 'Node':
node = root
while node:
head = tail = Node(0)
curr = node
while curr:
if curr.left:
tail.next = curr.left
tail = tail.next
if curr.right:
tail.next = curr.right
tail = tail.next
curr = curr.next
node = head.next
return root