Leetcode 102. Binary Tree Level Order Traversal
Description: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
Link: 102. Binary Tree Level Order Traversal
Examples:
Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ]
思路: 给定二叉树的root节点,按层返回值,每层一个list. 逐层遍历,保存每层所有节点的val到一个list, 所有的非None左右节点到一个list,即下一层待遍历的所有节点,直到节点list为空。
class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if root is None: return [] nodes = [root] vals = [] while nodes: temp = [] tempNodes = [] for n in nodes: temp.append(n.val) if not n.left is None: tempNodes.append(n.left) if not n.right is None: tempNodes.append(n.right) vals.append(temp) nodes = tempNodes return vals
日期: 2021-01-13 It has been long time that I didn't solve problems in leetcode because of preparing a paper experiments, but all these are excuses, so I should return back and stick to do it. New year, this is one of my targets.