xiannv / xiannv.github.io

blog
0 stars 0 forks source link

【剑指offer】python 面试题32 - III. 从上到下打印二叉树 III - 中等 #121

Open xiannv opened 4 years ago

xiannv commented 4 years ago

请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。

 

例如: 给定二叉树: [3,9,20,null,null,15,7],

3

/ \ 9 20 / \ 15 7 返回其层次遍历结果:

[ [3], [20,9], [15,7] ]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

xiannv commented 4 years ago

方法一

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
           return []
        deque = [root]
        result = []
        times = 1
        while deque:
            out = []
            temp = []
            while deque:
                k = deque.pop()
                temp.append(k.val)
                if times % 2:
                    if k.left:
                        out.append(k.left)
                    if k.right:
                        out.append(k.right)
                else:
                    if k.right:
                        out.append(k.right)
                    if k.left:
                        out.append(k.left)
            result.append(temp)
            deque = out
            times += 1
        return result