层次遍历,用到队列(先进先出).
queue.Queue()
collections.deque()
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from queue import Queue # queue 不是大写 class Solution: def levelOrder(self, root: TreeNode) -> List[int]: node = [] if root is None: return node # 当输入为[] q = Queue() q.put(root) while not q.empty(): out = q.get() node.append(out.val) if out.left is not None: # is not 不是 not q.put(out.left) if out.right is not None: q.put(out.right) return node
双端队列
class Solution: def levelOrder(self, root: TreeNode) -> List[int]: if not root: return [] res, queue = [], collections.deque() queue.append(root) while queue: node = queue.popleft() res.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return res
层次遍历,但要找到每一层最后一个节点
deque操作
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from queue import Queue from collections import deque class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] node = [] sub = [] last_node = root q = deque() q.append(root) while q: # 判断不为空 out = q.popleft() # 左侧出来 sub.append(out.val) if out.left is not None: # is not 不是 not q.append(out.left) if out.right is not None: q.append(out.right) if out==last_node: node.append(sub) sub = [] if q: # 如果没有下一层了 last_node = q.pop() # 右侧出来 q.append(last_node) # 右侧进去 return node
循环一层里面的节点,在循环下一层,因为读取第t层,不会含有t+2层
class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] res, queue = [], collections.deque() queue.append(root) while queue: tmp = [] for _ in range(len(queue)): node = queue.popleft() tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(tmp) return res
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
只能在加入到列表的时候操作,因为存储的队列要按照二叉树的结构。右边读取队列节点时,总时读最后一个,就不是二叉树结构了。
最后只需要加一个变量记录是奇数还是偶数,然后在sub列表中,左边加入或者右边加入。
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] node = [] sub = deque() # 列表变为双端队列 last_node = root q = deque() q.append(root) layer = 1 while q: # 判断不为空 out = q.popleft() # 左侧出来 if layer % 2: sub.append(out.val) else: sub.appendleft(out.val) if out.left is not None: # is not 不是 not q.append(out.left) if out.right is not None: q.append(out.right) if out==last_node: layer += 1 node.append(list(sub)) # 把队列换成list 注意可以转换的 sub = deque() if q: # 如果没有下一层了 last_node = q.pop() # 右侧出来 q.append(last_node) # 右侧进去 return node