LeetCode 题解工作台

从二叉树一个节点到另一个节点每一步的方向

给你一棵 二叉树 的根节点 root ,这棵二叉树总共有 n 个节点。每个节点的值为 1 到 n 中的一个整数,且互不相同。给你一个整数 startValue ,表示起点节点 s 的值,和另一个不同的整数 destValue ,表示终点节点 t 的值。 请找到从节点 s 到节点 t 的 最短路径 ,…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

我们可以先找到节点 和 的最近公共祖先,记为 ,然后分别从 出发,找到 和 的路径。那么从 到 的路径就是 的个数,从 到 的路径就是 的路径,最后将这两个路径拼接起来即可。 时间复杂度 ,空间复杂度 。其中 为二叉树的节点数。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一棵 二叉树 的根节点 root ,这棵二叉树总共有 n 个节点。每个节点的值为 1 到 n 中的一个整数,且互不相同。给你一个整数 startValue ,表示起点节点 s 的值,和另一个不同的整数 destValue ,表示终点节点 t 的值。

请找到从节点 s 到节点 t 的 最短路径 ,并以字符串的形式返回每一步的方向。每一步用 大写 字母 'L' ,'R' 和 'U' 分别表示一种方向:

  • 'L' 表示从一个节点前往它的 左孩子 节点。
  • 'R' 表示从一个节点前往它的 右孩子 节点。
  • 'U' 表示从一个节点前往它的  节点。

请你返回从 s 到 t 最短路径 每一步的方向。

 

示例 1:

输入:root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
输出:"UURL"
解释:最短路径为:3 → 1 → 5 → 2 → 6 。

示例 2:

输入:root = [2,1], startValue = 2, destValue = 1
输出:"L"
解释:最短路径为:2 → 1 。

 

提示:

  • 树中节点数目为 n 。
  • 2 <= n <= 105
  • 1 <= Node.val <= n
  • 树中所有节点的值 互不相同 。
  • 1 <= startValue, destValue <= n
  • startValue != destValue
lightbulb

解题思路

方法一:最近公共祖先 + DFS

我们可以先找到节点 startValue\textit{startValue}destValue\textit{destValue} 的最近公共祖先,记为 node\textit{node},然后分别从 node\textit{node} 出发,找到 startValue\textit{startValue}destValue\textit{destValue} 的路径。那么从 startValue\textit{startValue}node\textit{node} 的路径就是 U\textit{U} 的个数,从 node\textit{node}destValue\textit{destValue} 的路径就是 path\textit{path} 的路径,最后将这两个路径拼接起来即可。

时间复杂度 O(n)O(n),空间复杂度 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
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 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 getDirections(
        self, root: Optional[TreeNode], startValue: int, destValue: int
    ) -> str:
        def lca(node: Optional[TreeNode], p: int, q: int):
            if node is None or node.val in (p, q):
                return node
            left = lca(node.left, p, q)
            right = lca(node.right, p, q)
            if left and right:
                return node
            return left or right

        def dfs(node: Optional[TreeNode], x: int, path: List[str]):
            if node is None:
                return False
            if node.val == x:
                return True
            path.append("L")
            if dfs(node.left, x, path):
                return True
            path[-1] = "R"
            if dfs(node.right, x, path):
                return True
            path.pop()
            return False

        node = lca(root, startValue, destValue)

        path_to_start = []
        path_to_dest = []

        dfs(node, startValue, path_to_start)
        dfs(node, destValue, path_to_dest)

        return "U" * len(path_to_start) + "".join(path_to_dest)
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Look for an understanding of tree traversal techniques, especially in the context of Lowest Common Ancestor (LCA).

  • question_mark

    Check for an efficient approach, where the traversal doesn't revisit nodes unnecessarily.

  • question_mark

    Expect clarity in constructing the path with the correct sequence of 'L', 'R', and 'U' directions.

warning

常见陷阱

外企场景
  • error

    Confusing the order of traversal—ensure the solution moves up first and then down to the destination node.

  • error

    Overcomplicating the LCA search—opt for a simple recursive or iterative approach.

  • error

    Failing to handle edge cases, such as when the start node is the parent of the destination node.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    The problem can be varied by providing additional constraints, such as limiting the tree to binary search trees (BST).

  • arrow_right_alt

    Another variant might require returning the path as an array of node values instead of directions.

  • arrow_right_alt

    For larger trees, the pathfinding method could be tested with variations in node depth or balance.

help

常见问题

外企场景

从二叉树一个节点到另一个节点每一步的方向题解:二分·树·traversal | LeetCode #2096 中等