242. Convert Binary Tree to Linked Lists by Depth

层序遍历 => BFS

就是加了点链表操作

class Solution:
    # @param {TreeNode} root the root of binary tree
    # @return {ListNode[]} a lists of linked list
    def binaryTreeToLists(self, root):
        if not root: return []
        # Write your code here
        res = []
        q = collections.deque([root])
        
        while q:
            width = len(q)
            for _ in range(width):
                node = q.popleft()
                if _ == 0:
                    level = ListNode(node.val)
                    cur = level
                else:
                    cur.next = ListNode(node.val)
                    cur = cur.next
                if node.left: q.append(node.left)
                if node.right: q.append(node.right)
            res.append(level)
            
        return res

Last updated

Was this helpful?