二叉树的层序遍历:
给定一个二叉树,层序遍历输出
输入:[3,9,20,null,null,15,7]
输出:[[3],[9],[20],[15],[7]]
# 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 = [] queue = [] queue.append(root) while queue: node = queue.pop(0) res.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return res
二叉树的层序遍历(层层打印):
输入:[3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] res = [] queue = [] queue.append(root) while queue: tmp = [] for _ in range(len(queue)): node = queue.pop(0) tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(tmp) return res
二叉树层序遍历(层层打印):
偶数层倒序
输入:[3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]
class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] res = [] queue = [] queue.append(root) while queue: tmp = [] for _ in range(len(queue)): node = queue.pop(0) tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(tmp[::-1] if len(queue)%2 else tmp) return res
参考链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof/solution/mian-shi-ti-32-ii-cong-shang-dao-xia-da-yin-er-c-5/