130、二叉树的之字形层序遍历

2018-08-01  本文已影响0人  小碧小琳

leetcode103
思路1:

思路2:

代码:
注意用列表表示队列时,每次添加元素都是用insert方法。

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

class Solution:
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """

        def search_func(Q_para):
            Q_res = []
            L_res = []
            while Q_para:
                node = Q_para.pop()
                if node.left:
                    Q_res.insert(0,node.left)
                    L_res.append(node.left.val)
                if node.right:
                    Q_res.insert(0,node.right)
                    L_res.append(node.right.val)
            return Q_res,L_res
        if root:
            results = []
            Que = [root]
            L1 = [root.val]
            n = 0
            while Que:
                if n%2 == 0:
                    results.append(L1)
                else:
                    L1.reverse()
                    results.append(L1)
                Que,L1 = search_func(Que)
                n += 1
            return results
            
        else:
            return []
上一篇下一篇

猜你喜欢

热点阅读