温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

剑指offer:从上到下打印二叉树

发布时间:2020-06-23 20:29:15 来源:网络 阅读:307 作者:Jayce_SYSU 栏目:编程语言

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

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    """
    由于需要逐层打印,那么我们在遍历整棵树的时候就需要维护一个队列。
    队列中存储的是下一层从左到右的节点。
    具体来说在打印第k层的节点的时候,将该节点的左右子节点按顺序入队即可。递归出口就是队列为空
    """
    def PrintFromTopToBottom(self, root):
        def helper(root_queue, ans):
            # 递归出口即队列为空
            if not root_queue:
                return
            length = len(root_queue)
            for i in range(length):
                # 对于某个节点,在打印完它的值之后,将其左右子节点先后入队
                ans.append(root_queue[i].val)
                if root_queue[i].left:
                    root_queue.append(root_queue[i].left)
                if root_queue[i].right:
                    root_queue.append(root_queue[i].right)

            helper(root_queue[length:], ans)

        res = []
        if not root:
            return res
        helper([root], res)
        return res

def main():
    root = TreeNode(8)
    root.left = TreeNode(6)
    root.right = TreeNode(10)
    root.left.left = TreeNode(5)
    root.left.right = TreeNode(7)
    root.right.left = TreeNode(9)
    root.right.right = TreeNode(11)

    solution = Solution()
    print(solution.PrintFromTopToBottom(root))

if __name__ == '__main__':
    main()
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI