LeetCode 题解工作台

N 叉树的前序遍历

给定一个 n 叉树的根节点 root ,返回 其节点值的 前序遍历 。 n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。 示例 1: 输入: root = [1,null,3,2,4,null,5,6] 输出: [1,3,5,6,2,4] 示例 2: 输入…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 二分·树·traversal

bolt

答案摘要

我们可以递归地遍历整棵树。对于每个节点,先将节点的值加入答案,然后对该节点的每个子节点递归地调用函数。 时间复杂度 ,空间复杂度 。其中 为节点数。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个 n 叉树的根节点  root ,返回 其节点值的 前序遍历

n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。


示例 1:

输入:root = [1,null,3,2,4,null,5,6]
输出:[1,3,5,6,2,4]

示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]

 

提示:

  • 节点总数在范围 [0, 104]
  • 0 <= Node.val <= 104
  • n 叉树的高度小于或等于 1000

 

进阶:递归法很简单,你可以使用迭代法完成此题吗?

lightbulb

解题思路

方法一:递归

我们可以递归地遍历整棵树。对于每个节点,先将节点的值加入答案,然后对该节点的每个子节点递归地调用函数。

时间复杂度 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
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""


class Solution:
    def preorder(self, root: "Node") -> List[int]:
        def dfs(root):
            if root is None:
                return
            ans.append(root.val)
            for child in root.children:
                dfs(child)

        ans = []
        dfs(root)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Assess the candidate's understanding of depth-first search and stack manipulation.

  • question_mark

    Evaluate how well the candidate manages tree traversal and stack management under constraints.

  • question_mark

    Check for the candidate's ability to handle edge cases like empty trees or null nodes.

warning

常见陷阱

外企场景
  • error

    Mismanagement of stack operations leading to incorrect node order during traversal.

  • error

    Failure to handle empty trees or null child nodes.

  • error

    Over-complicating the solution with unnecessary recursion or additional data structures.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Implement the same traversal using recursion instead of a stack.

  • arrow_right_alt

    Modify the approach to handle different N-ary tree traversal patterns, such as postorder or level-order.

  • arrow_right_alt

    Adapt the solution to return only the first k nodes from the traversal.

help

常见问题

外企场景

N 叉树的前序遍历题解:二分·树·traversal | LeetCode #589 简单