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[::-1] if len(res) % 2 else tmp) return res
# 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 [] res, stack = [],[root] while stack: tmp = [] for _ in range(len(stack)): node = stack.pop(0) if len(res) &1: tmp.insert(0,node.val) # 偶数层 -> 队列头部 else: tmp.append(node.val) # 奇数层 -> 队列尾部 if node.left: stack.append(node.left) if node.right: stack.append(node.right) res.append(list(tmp)) return res
# 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 [] res, stack = [],[root] while stack: tmp = [] for _ in range(len(stack)): node = stack.pop(0) tmp.append(node.val) # 奇数层 -> 队列尾部 if node.left: stack.append(node.left) if node.right: stack.append(node.right) res.append(tmp[::-1] if len(res)&1 else tmp) return res
本文来自博客园,作者:topass123,转载请注明原文链接:https://www.cnblogs.com/topass123/p/12766739.html