LeetCode 题解工作台

二叉树中的最长交错路径

给你一棵以 root 为根的二叉树,二叉树中的交错路径定义如下: 选择二叉树中 任意 节点和一个方向(左或者右)。 如果前进方向为右,那么移动到当前节点的的右子节点,否则移动到它的左子节点。 改变前进方向:左变右或者右变左。 重复第二步和第三步,直到你在树中无法继续移动。 交错路径的长度定义为: 访…

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

时间复杂度 ,其中 是树中节点的个数。 class Solution:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵以 root 为根的二叉树,二叉树中的交错路径定义如下:

  • 选择二叉树中 任意 节点和一个方向(左或者右)。
  • 如果前进方向为右,那么移动到当前节点的的右子节点,否则移动到它的左子节点。
  • 改变前进方向:左变右或者右变左。
  • 重复第二步和第三步,直到你在树中无法继续移动。

交错路径的长度定义为:访问过的节点数目 - 1(单个节点的路径长度为 0 )。

请你返回给定树中最长 交错路径 的长度。

 

示例 1:

输入:root = [1,null,1,1,1,null,null,1,1,null,1,null,null,null,1,null,1]
输出:3
解释:蓝色节点为树中最长交错路径(右 -> 左 -> 右)。

示例 2:

输入:root = [1,1,1,null,1,null,null,1,1,null,1]
输出:4
解释:蓝色节点为树中最长交错路径(左 -> 右 -> 左 -> 右)。

示例 3:

输入:root = [1]
输出:0

 

提示:

  • 每棵树最多有 50000 个节点。
  • 每个节点的值在 [1, 100] 之间。
lightbulb

解题思路

方法一:DFS

时间复杂度 O(n)O(n),其中 nn 是树中节点的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 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:
        def dfs(root, l, r):
            if root is None:
                return
            nonlocal ans
            ans = max(ans, l, r)
            dfs(root.left, r + 1, 0)
            dfs(root.right, 0, l + 1)

        ans = 0
        dfs(root, 0, 0)
        return ans
speed

复杂度分析

指标
时间O(n)
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Are you correctly flipping direction at each step?

  • question_mark

    Have you considered updating a global maximum instead of returning only local values?

  • question_mark

    Can your DFS handle the largest trees efficiently without recomputation?

warning

常见陷阱

外企场景
  • error

    Forgetting to subtract one from node count to get ZigZag length.

  • error

    Only tracking one direction from root instead of both left and right.

  • error

    Not updating the global maximum at every node, missing longer subpaths.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Compute longest ZigZag path starting specifically from leaf nodes only.

  • arrow_right_alt

    Return the actual sequence of node values forming the longest ZigZag.

  • arrow_right_alt

    Count ZigZag paths that exceed a given minimum length instead of maximum.

help

常见问题

外企场景

二叉树中的最长交错路径题解:二分·树·traversal | LeetCode #1372 中等