剑指offer 23. 从上往下打印二叉树

原题

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

Reference Answer

解题思路:
在这里插入图片描述
思路:用一个临时数组存储需要打印的节点,如打印8时,将6和10存入临时数组

# -*- 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 []
        temp = []
        res = []
        temp.append(root)
        while temp:
            temp_count = temp.pop(0)
            res.append(temp_count.val)
            if temp_count.left:
                temp.append(temp_count.left)
            if temp_count.right:
                temp.append(temp_count.right)
        return res
        

Note

这道题解题方式很巧妙,题目本意是一种二叉树遍历,但是若是想分层遍历,采用将下一轮结果存在temp变量,每轮处理一轮,再加一轮,很巧妙。

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/83624844