Reverse Odd Levels of Binary Tree - LeetCode

 

 

 

 

 

머 이런 문제가 다 있냐? 휴

리트코드라는 사이트에 아직 익숙하지 않아서 어떻게 풀으라는 건지 좀 감이 안 왔다.

LeetCode 2415 Reverse odd levels of Binary Tree Python Solution (youtube.com)

이 유튜브의 설명을 참고해서 공부해가면서 풀어 보았다.

DFS로 재귀함수를 계속 호출해서 푸는 방법이다. 

 

 

class Solution(object):
    def reverseOddLevels(self, root):

        """
        :type root: Optional[TreeNode]
        :rtype: Optional[TreeNode]
        """

        def helper(root1, root2, depth):
            if root1 is None and root2 is None:
                return None
            if depth % 2 != 0:
                tmp = root1.val
                root1.val = root2.val
                root2.val = tmp
        
            helper(root1.left, root2.right, depth +1)
            helper(root1.right, root2.left, depth +1)

        helper(root.left, root.right, 1)
        return root

 

+ Recent posts