바위타는 두루미

[leetcode]103. Binary Tree Zigzag Level Order Traversal 본문

Study/Algorithm

[leetcode]103. Binary Tree Zigzag Level Order Traversal

DoRoMii 2019. 8. 9. 11:40
728x90

103. Binary Tree Zigzag Level Order Traversal

 

Given a binary tree, return the zigzag level ordertraversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree [3,9,20,null,null,15,7],

              3

             / \

           9  20

                / \

             15   7

return its zigzag level order traversal as:

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

class Solution(object):
    def zigzagLevelOrder(self, root):
        level = 0
        result = []
        parents = []
        currents = []
        if root :
            currents.append(root)
        while currents:
            tmp =[]
            parents = currents
            currents = []
            for p in parents:
                tmp.append(p.val)
                if p.left :
                    currents.append(p.left)
                if p.right :
                    currents.append(p.right)
           
            result.append(tmp if level %2 ==0 else tmp[::-1] )
            level +=1
            
        return result

 

 

 

 

 

Comments