Given a binary tree
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.
用层序遍历的方式,把每一层节点存在一个list中。
然后进行处理比较容易。
class Solution:
def connect(self, root: 'Node') -> 'Node':
if root is None:return root
level = [root]
root.next=None
while level:
temp=[]
for i in range(len(level)-1):
level[i].next=level[i+1]
for node in level:
if node.left:
temp.append(node.left)
if node.right:
temp.append(node.right)
level=temp
return root
二叉树层序遍历与填充Next指针

本文介绍了一种解决二叉树问题的算法,通过层序遍历将二叉树的每个节点的next指针指向其右侧的下一个节点。如果节点右侧没有节点,则next指针设为NULL。此算法首先将根节点放入列表,然后逐层处理,更新next指针,并将下一层的节点加入列表。
467

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



