628 Star 6.8K Fork 3.1K

陌溪 / LearningNotes

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 929 Bytes
一键复制 编辑 原始数据 按行查看 历史
陌溪 提交于 2020-05-29 16:15 . add code and update README.md

从上往下打印二叉树

来源

https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701

题目

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

代码

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    # 返回从上到下每个节点值列表,例:[1,2,3]
    def PrintFromTopToBottom(self, root):
        if root == None:
            return []
        # 将输入的节点存入support中
        support = [root]
        ret = []
        while support:
            tempNode = support[0]
            ret.append(tempNode.val)
            if tempNode.left:
                support.append(tempNode.left)
            if tempNode.right:
                support.append(tempNode.right)
            # 删除已经输出的节点
            del support[0]
        return ret
1
https://gitee.com/moxi159753/LearningNotes.git
git@gitee.com:moxi159753/LearningNotes.git
moxi159753
LearningNotes
LearningNotes
master

搜索帮助