剑指offer-从上往下打印二叉树(python)

这题关键在于实时更新list,先pop在加进去left和right

# -*- coding:utf-8 -*-
# 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 []
        all_list=[root]
        res=[]
        while all_list:
            tmp=all_list.pop(0)
            if tmp.left:
                all_list.append(tmp.left)
            if tmp.right:
                all_list.append(tmp.right)
            res.append(tmp.val)
        return res
        
    
发布了69 篇原创文章 · 获赞 46 · 访问量 5268

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104237359
今日推荐