A / \ B C / \ / \ D E F G
We extend the concept of linked data structures to structure containing nodes with more than one self-referenced field. A binary tree is made of nodes, where each node contains a "left" reference, a "right" reference, and a data element. The topmost node in the tree is called the root.
Every node (excluding a root) in a tree is connected by a directed edge from exactly one other node. This node is called a parent. On the other hand, each node can be connected to arbitrary number of nodes, called children. Nodes with no children are called leaves, or external nodes. Nodes which are not leaves are called internal nodes. Nodes with the same parent are called siblings.
- Queues are open from both ends meaning elements are added from the back and removed from the front
- The element to be added first is removed first (First In First Out - FIFO)
- If all the elements are removed, then the queue is empty and if you try to remove elements from an empty queue, a warning or an error message is thrown.
- If the queue is full and you add more elements to the queue, a warning or error message must be thrown.
import queue # From class queue, Queue is # created as an object Now L # is Queue of a maximum # capacity of 20 L = queue.Queue(maxsize=20) # Data is inserted into Queue # using put() Data is inserted # at the end L.put(5) L.put(9) L.put(1) L.put(7) # get() takes data out from # the Queue from the head # of the Queue print(L.get()) print(L.get()) print(L.get()) print(L.get())
from collections import deque """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A Tree @return: Level order a list of lists of integer """ def levelOrder(self, root): if root is None: return  queue = deque([root]) result =  while queue: level =  for _ in range(len(queue)): node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level) return result
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。