码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode]题解(python):102 Binary Tree Level Order Traversal

时间:2016-05-17 17:41:10      阅读:425      评论:0      收藏:0      [点我收藏+]

标签:

题目来源


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

标签:

原文地址:http://www.cnblogs.com/loadofleaf/p/5502285.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!