Binary Tree Level Order Traversal

Question

Problem Statement

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

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]
]

Challenge

Challenge 1: Using only 1 queue to implement it.

Challenge 2: Use DFS algorithm to do it.

题解 - 使用队列

此题为广搜的基础题,使用一个队列保存每层的节点即可。出队和将子节点入队的实现使用 for 循环,将每一轮的节点输出。

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    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):
        res=[]
        self.preorder(root, 0, res)
        return res
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        this.val = val
        this.left, this.right = None, None
"""


class Solution:
    """
    @param root: The root of binary tree.
    @return: Level order in a list of lists of integers
    """
    def levelOrder(self, root):
        # write your code here
        self.results = []
        if not root:
            return self.results
        q = [root]
        while q:
            new_q = []
            self.results.append([n.val for n in 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 self.results

源码分析

  1. 异常,还是异常
  2. 使用STL的queue数据结构,将root添加进队列
  3. 遍历当前层所有节点,注意需要先保存队列大小,因为在入队出队时队列大小会变化
  4. list保存每层节点的值,每次使用均要初始化

复杂度分析

使用辅助队列,空间复杂度 $$O(n)$$, 时间复杂度 $$O(n)$$.

results matching ""

    No results matching ""