GoCalf Calf 的自留地 · 昙花一现

2415. Reverse Odd Levels of Binary Tree

Problem

Given the root of a perfect binary tree, reverse the node values at each odd level of the tree.

  • For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2].

Return the root of the reversed tree.

A binary tree is perfect if all parent nodes have two children and all leaves are on the same level.

The level of a node is the number of edges along the path between it and the root node.

https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/

Example 1:

case1
case1

Input: root = [2,3,5,8,13,21,34]
Output: [2,5,3,8,13,21,34]
Explanation:
The tree has only one odd level.
The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3.

Example 2:

case2
case2

Input: root = [7,13,11]
Output: [7,11,13]
Explanation:
The nodes at level 1 are 13, 11, which are reversed and become 11, 13.

Example 3:

Input: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2]
Output: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]
Explanation:
The odd levels have non-zero values.
The nodes at level 1 were 1, 2, and are 2, 1 after the reversal.
The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal.

Constraints:

  • The number of nodes in the tree is in the range [1, 2¹⁴].
  • 0 <= Node.val <= 10⁵
  • root is a perfect binary tree.

Test Cases

python
# 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 reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
solution_test.py下载完整源码
py
import pytest

import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from _utils.binary_tree import build_tree, print_tree
from solution import Solution


@pytest.mark.parametrize('root, expected', [
    ([2,3,5,8,13,21,34], [2,5,3,8,13,21,34]),
    ([7,13,11], [7,11,13]),
    ([0,1,2,0,0,0,0,1,1,1,1,2,2,2,2], [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1]),
])
@pytest.mark.parametrize('sol', [Solution()])
def test_solution(sol, root, expected):
    result = sol.reverseOddLevels(build_tree(root))
    assert print_tree(result) == expected

Thoughts

直接按层序(level-order)遍历二叉树,把奇数层的节点翻转。但需要处理好翻转之后,偶数层和上一个奇数层之间的连接。

开始想像 102. Binary Tree Level Order Traversal 一样做基于队列的非递归层序遍历,但是满二叉树可以简化很多,用数组保存当前层,直接遍历一遍下一层的节点全取出来即可。

时间复杂度 O(n),空间复杂度 O(n)。

Code

py
# Definition for a binary tree node.
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root: return None

        parents = [root]
        reverse = True
        while parents[0].left:
            if reverse:
                children = [c for node in reversed(parents) for c in (node.right, node.left)]
            else:
                children = [c for node in reversed(parents) for c in (node.left, node.right)]

            j = 0
            for node in parents:
                node.left = children[j]
                node.right = children[j+1]
                j += 2

            parents = children
            reverse = not reverse

        return root

评论需要 JavaScript。