LeetCode117. Populating Next Right Pointers in Each Node II(思路及python解法)

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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值