首页 > 编程语言 > 详细

leetcode-python-填充每个节点的下一个右侧节点指针

时间:2021-06-17 16:49:38      阅读:15      评论:0      收藏:0      [点我收藏+]

设置p为根节点,设置判断count,长度为当前层长度

逐个遍历节点,若左右节点存在则加入,随后删除头节点。

当count=1时,为当前层最后一个节点的时候,p指向None。删除头节点,p指向下一层开头

若count != 1,则正常向后指

"""
# 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 None
        p = root
        nexttemp = [p]
        length = len(nexttemp)
        count = length
        while count > 0 :
            head = nexttemp[0]
            if count == 1:
                p.next = None
                count -= 1
                if head.left and head.right:
                    nexttemp.append(head.left)
                    nexttemp.append(head.right)
                del nexttemp[0]
                if nexttemp == []:
                    break
                p = nexttemp[0]
                length = len(nexttemp)
                count = length
            else:
                p.next = nexttemp[1]
                count -= 1
                if head.left and head.right:
                    nexttemp.append(head.left)
                    nexttemp.append(head.right)
                del nexttemp[0]
                p = p.next
        return root

            
            

        
        

 

leetcode-python-填充每个节点的下一个右侧节点指针

原文:https://www.cnblogs.com/cbachen/p/14893872.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!