Участник:Ковальков Антон М05-903б/Longest ZigZag Path in a Binary Tree

Материал из DISCOPAL
Перейти к: навигация, поиск

https://leetcode.com/problems/longest-zigzag-path-in-a-binary-tree/

Python3

# 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 longestZigZag(self, root: TreeNode) -> int:
        queue = [(root.left, True), (root.right, False)]
 
        def go(root, is_right):
            if not root:
                return 0
 
            if is_right:
                next_branch = root.right
                other_branch = root.left
            else:
                next_branch = root.left
                other_branch = root.right
            if other_branch:
                queue.append((other_branch, is_right))
            return 1 + go(next_branch, not is_right)
 
        res = 0
        while queue:
            current, is_right = queue.pop(0)
            if current:
                res = max(res, go(current, is_right))
        return res