从上往下打印二叉树(二叉树)

来源:互联网 发布:机器学习实战smo算法 编辑:程序博客网 时间:2024/06/05 00:24

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。


由题目很容易知道,层次遍历,用列表模拟队列操作即可

# -*- coding:utf-8 -*-# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    # 返回从上到下每个节点值列表,例:[1,2,3]    def PrintFromTopToBottom(self, root):        # 二叉树的层次遍历        # write code here        if root is None:            return []        li = []        que = [root]        while len(que) > 0:            tree = que.pop(0)                        if tree is not None:                li.append(tree.val)                que.append(tree.left)                que.append(tree.right)        return li


0 0
原创粉丝点击