本文主要是介绍117. 填充同一层的兄弟节点 II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/
和116一样层序
import Queue
class Solution:# @param root, a tree link node# @return nothingdef connect(self, root):if not root:return Noneq = Queue.Queue()q.put(root)while not q.empty():count = q.qsize()last = Nonefor _ in range(count):node = q.get()if last:last.next = nodelast = nodeif node.left:q.put(node.left)if node.right:q.put(node.right)
递归:注意不能前序,应该先递归处理右子树再左。因为每次处理root时得用到root.next的信息,所以必须先对右侧处理。
class Solution:# @param root, a tree link node# @return nothingdef connect(self, root):self.helper(root)def helper(self, root):if not root: #出口return#若有左子,且有右子,则左子连接右子#无右子,则左子连接父亲右侧的左(或右)子if root.left:if root.right:root.left.next = root.right else:next = root.nextwhile next:if next.left:root.left.next = next.leftbreakif next.right:root.left.next = next.rightbreaknext = next.next#若有右子,连接父亲右侧的左(或右)子if root.right:next = root.nextwhile next:if next.left:root.right.next = next.leftbreakif next.right:root.right.next = next.rightbreaknext = next.nextself.helper(root.right)self.helper(root.left)
这篇关于117. 填充同一层的兄弟节点 II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!