[LeetCode]题解(python):102 Binary Tree Level Order Traversal
Posted loadofleaf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]题解(python):102 Binary Tree Level Order Traversal相关的知识,希望对你有一定的参考价值。
题目来源
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
以上是关于[LeetCode]题解(python):102 Binary Tree Level Order Traversal的主要内容,如果未能解决你的问题,请参考以下文章
精选力扣500题 第13题 LeetCode 102. 二叉树的层序遍历c++详细题解