Wins the offer - the breadth of the tree traversal

Title Description

Downward from the print out of each node of the binary tree, with the layer node from left to right printing. If no nodes, do not print. Output a list

 

Thinking

The need to use a FIFO queue, recursive, then, is the depth-first traversal, not breadth-first traversal

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def PrintFromTopToBottom(self, root):
        if not root:
            return []
        
        queen = [root]
        ans = []
        while len(queen)>0:
            root = queen[0]
            ans.append(root.val)
            if root.left:
                queen.append(root.left)
            if root.right:
                queen.append(root.right)
            del queen[0]
        return ans

 

Published 82 original articles · won praise 2 · Views 4365

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104745030