102. Binary Tree Level Order Traversal [easy] (Python)

题目链接

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

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

题目翻译

给定一个二叉树,返回所有节点值的层序遍历结果。(从左到右,从上到下遍历)
比如,给出二叉树:{3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

它的层序遍历结果为:

[
  [3],
  [9,20],
  [15,7]
]

思路方法

思路一

层序遍历的一般想法,做广度优先遍历(BFS)。遍历的同时,注意记录遍历结果要用满足题目要求的输出格式。

代码

# 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]]
        """
        res = []
        if root == None:
            return res

        q = [root]
        while len(q) != 0:
            res.append([node.val for node in q])
            new_q = []
            for node in q:
                if node.left:
                    new_q.append(node.left)
                if node.right:
                    new_q.append(node.right)
            q = new_q

        return res

思路二

用深度优先搜索(DFS),节点的深度与输出结果数组的下标相对应。注意在递归的时候要保存每次访问的节点值。

代码

# 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]]
        """
        res = []
        self.dfs(root, 0, res)
        return res

    def dfs(self, root, depth, res):
        if root == None:
            return res
        if len(res) < depth+1:
            res.append([])
        res[depth].append(root.val)
        self.dfs(root.left, depth+1, res)
        self.dfs(root.right, depth+1, res)

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51363095

你可能感兴趣的:(LeetCode,LeetCode解题报告)