HTMLify

LeetCode - Reverse Odd Levels of Binary Tree - Python
Views: 3 | Author: abh
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def get_level(self, root, level: int) -> List[TreeNode]:
        level_elements = []
        que = [[root]]
        i = 0
        while i < level:
            s_que = []
            for node in que[i]:
                s_que.append(node.left)
                s_que.append(node.right)
            que.append(s_que)
            i+= 1
        return que[-1]

    def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        levels = 0
        head = root
        while head.left:
            levels += 1
            head = head.left
        for l in range(1, levels+1, 2):
            elements = self.get_level(root, l)
            rev_values = []
            for e in reversed(elements):
                rev_values.append(e.val)
            for i, e in enumerate(elements):
                e.val = rev_values[i]
        return root

Comments