Old Wei wins the offer to take you to learn --- Brush title series (22 from the print binary tree down)

22. The print binary tree from the top down

problem:

Downward from the print out of each node of the binary tree, with the layer node from left to right printing.

solve:

thought:

This question is the level of study tree traversal, in fact, and graph theory breadth-first traversal is very similar, only need to be modified to place part. Breadth-first traversal of graph theory can look past the old guard of the blog: the old guard to take you to learn - DFS must Shredded depth-first traversal of the BFS breadth-first traversal (dry !!! attached python code)

python code:

# -*- coding:utf-8 -*-
from collections import deque
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        # write code here
        if(not root):
            return []
        Q=deque()
        Q.append(root)
        result=[]
        while Q:
            u=Q.popleft()
            if u.left!=None:
                Q.append(u.left)
            if(u.right!=None):
                Q.append(u.right)
            result.append(u.val)
        return result
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/104931247