题目来源
https://leetcode.com/problems/binary-tree-level-order-traversal/
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
题意分析
Input: 一个二叉树
Output:一个每层数值组合的list
Conditions:层次遍历
题目思路
采用dfs,先序遍历的方法,采用一个level值来记录高度,注意要适时扩充list的size
AC代码(Python)
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def preorder(self, root, level, res): 10 if root: 11 if len(res) < level + 1: res.append([]) 12 res[level].append(root.val) 13 self.preorder(root.left, level + 1, res) 14 self.preorder(root.right, level + 1, res) 15 def levelOrder(self, root): 16 """ 17 :type root: TreeNode 18 :rtype: List[List[int]] 19 """ 20 res = [] 21 self.preorder(root, 0, res) 22 print res 23 return res