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

时间:2022-06-15 22:45:14

题目来源


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)

 # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def preorder(self, root, level, res):
if root:
if len(res) < level + 1: res.append([])
res[level].append(root.val)
self.preorder(root.left, level + 1, res)
self.preorder(root.right, level + 1, res)
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
res = []
self.preorder(root, 0, res)
print res
return res