首页 > 代码库 > LeetCode 102. Binary Tree Level Order Traversal

LeetCode 102. 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).

For example:
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]]

 

解题思路

思路一

  • 先递归求出该树的深度,接着根据深度初始化结果的数组,最后通过递归,将每一层的值依次添加到答案中
# 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 levelOrder(self, root):        """        :type root: TreeNode        :rtype: List[List[int]]        """        if root == None:            return []        dep = self.depth(root)        self.ret = [[] for i in range(dep)]        self.helper(root, 0)        return self.ret            def helper(self, node, dep):        if node == None:            return        self.ret[dep].append(node.val)        self.helper(node.left, dep + 1)        self.helper(node.right, dep + 1)                def depth(self, node):        if node == None:            return 0        return max(self.depth(node.left), self.depth(node.right)) + 1

  

 

思路二

  • 利用栈来实现,将每一层的节点压入栈中,然后通过迭代遍历出每一层节点中的值并加入答案中
# 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 levelOrder(self, root):        """        :type root: TreeNode        :rtype: List[List[int]]        """             if root == None:            return []        stack, ret = [root], []        while stack:            level_value = http://www.mamicode.com/[]>

  

 

LeetCode 102. Binary Tree Level Order Traversal