码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 102. Binary Tree Level Order Traversal

时间:2017-05-25 11:47:44      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:solution   one   help   turn   level   tac   max   block   思路   

原题

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 = []
            next_level = []
            for node in stack:
                level_value.append(node.val)
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
            ret.append(level_value)
            stack = next_level
        return ret
                
            
            

  

 

LeetCode 102. Binary Tree Level Order Traversal

标签:solution   one   help   turn   level   tac   max   block   思路   

原文地址:http://www.cnblogs.com/LiCheng-/p/6902352.html

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