leetcode 117. 填充每个节点的下一个右侧节点指针 II python

本文探讨了如何通过层序遍历和递归方法连接二叉树节点,包括使用队列实现的层序遍历策略,以及递归寻找并设置节点间的next指针。两种方法应用于解决二叉树结构的连接问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

 

 题解一:层序遍历 通过

1.对二叉树进行层序遍历(通过借助队列实现),将各个节点按照层序遍历结果保存在list中。

2.将每层层序遍历结果中除了最后一个节点的next设置为当前层下一个节点,最后一个节点的next设置为None。

class Solution(object):
    def connect(self, root):
        noderes = []
        layers = []
        if root==None:
            return root
        layer = []
        layer.append(root)
        noderes.append(layer)
        while noderes:
            nowlayer = noderes[0]
            noderes.remove(nowlayer)
            layers.append(nowlayer)
            newlayer = []
            for node in nowlayer:
                if node.left:
                    newlayer.append(node.left)
                if node.right:
                    newlayer.append(node.right)
            if len(newlayer)>0:
                noderes.append(newlayer)
        for eachlayer in layers:
            for i in range(len(eachlayer)-1):
                eachlayer[i].next = eachlayer[i+1]
            eachlayer[-1].next = None
        return root

 题解二:递归

参考https://blog.youkuaiyun.com/qq_32424059/article/details/90487297

1.如果root左右子节点都存在,left.next则为右子节点,right.next为root.next的子节点(左子节点如果存在则为左子节点,否则为右子节点,如果都不存在,则找到root.next.next,如果都不存在则填充为None)

2.因此创建一个函数findcousin(node,parent) ,node为parent的子节点,该函数试图在root的cousin节点中找到一个有子节点的,并将node.next设置为该cousin节点的左子节点(如果存在)或右子节点。

3.如果root 左右子节点均存在,left.next即为right,然后对root.right调用findcousin,如果只有left,则对left调用findcousin,如果只有right,则对right调用。

4.对root的左右子树调用connect,需要先对right进行处理,因为findcousin需要用到该层当前节点之后的信息。

class Solution(object):
    def connect(self, root):
        if root==None:
            return root
        def findcousin(node,parent):
            tmp = parent.next
            while tmp:
                if tmp.left:
                    node.next = tmp.left
                    break
                elif tmp.right:
                    node.next = tmp.right
                    break
                tmp = tmp.next
        if root.left and root.right:
            root.left.next = root.right
            findcousin(root.right,root)
        elif root.left:
            findcousin(root.left,root)
        elif root.right:
            findcousin(root.right,root)
        self.connect(root.right)
        self.connect(root.left)
        return root

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值