如何将列表中的奇数索引元素反转?

时间:2019-05-20 19:57:50

标签: python list tree reverse breadth-first-search

这个想法是找到一棵树的之字形水平顺序遍历。 我的方法是找到遍历顺序,然后反转在奇数位置的元素。 但是,提交的测试用例以及预期的输出与我的实际输出不同。

# 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 zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        #for all odd number indices, reverse the list 

        ret = self.levelorder(root)
        print ret


    def levelorder(self,root):
        #first conduct a level order traversal 
        #then check the level
        #if the level is odd, then reverse the elements in the list 
        #otherwise, just print as is. 
        returnlist = [] 
        if not root: #check for null root 
            return returnlist

        q = [(root,0)]
        if root: 
            while q:
                node, level = q.pop(0) # store node object and level 
                if len(returnlist) < level + 1:
                    returnlist.append([node.val])
                else:
                    returnlist[level].append(node.val)
                    if level % 2 != 0:
                        returnlist[level].reverse() 
                if node.left:
                    q.append((node.left, level + 1))
                if node.right:
                    q.append((node.right, level+1))
        return returnlist

testcase = [0,2,4,1,None,3,-1,5,1,None,6,None,8,20,None,3,5,None,6,7,None,4,5,6,7]

标准输出 [[0], [4, 2], [1, 3, -1], [8, 1, 5, 6], [20, 3, 5, 6, 7], [7, 5, 4, 6]]

预期 [[0],[4,2],[1,3,-1],[8,6,1,5],[20,3,5,6,7],[7,6,5,4]]

0 个答案:

没有答案