You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *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.
注意保存下一层最左面的点,也就是next。
剩下就是判断当前点cur是否是这一层最右面的点。
总体还是比较简单的。
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:return root
cur = root
next = root.left
while cur.left:
cur.left.next = cur.right
if cur.next:
cur.right.next=cur.next.left
cur=cur.next
else:
cur=next
next=cur.left
return root
完美二叉树节点连接算法

本文介绍了一种用于完美二叉树的算法,旨在连接每个节点的next指针到其右侧相邻节点,若无相邻节点则设为NULL。通过迭代方式实现,保持下一层最左侧节点的next指针,并判断当前节点是否为该层最右侧节点。
741

被折叠的 条评论
为什么被折叠?



