LeetCode 题解工作台

从先序遍历还原二叉树

我们从二叉树的根节点 root 开始进行深度优先搜索。 在遍历中的每个节点处,我们输出 D 条短划线(其中 D 是该节点的深度),然后输出该节点的值。( 如果节点的深度为 D ,则其直接子节点的深度为 D + 1 。根节点的深度为 0 )。 如果节点只有一个子节点,那么保证该子节点为左子节点。 给出…

category

4

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 二分·树·traversal

bolt

答案摘要

/ * Definition for a binary tree node.

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

我们从二叉树的根节点 root 开始进行深度优先搜索。

在遍历中的每个节点处,我们输出 D 条短划线(其中 D 是该节点的深度),然后输出该节点的值。(如果节点的深度为 D,则其直接子节点的深度为 D + 1。根节点的深度为 0)。

如果节点只有一个子节点,那么保证该子节点为左子节点。

给出遍历输出 S,还原树并返回其根节点 root

 

示例 1:

输入:"1-2--3--4-5--6--7"
输出:[1,2,5,3,4,6,7]

示例 2:

输入:"1-2--3---4-5--6---7"
输出:[1,2,5,3,null,6,null,4,null,7]

示例 3:

输入:"1-401--349---90--88"
输出:[1,401,null,349,88,90]

 

提示:

  • 原始树中的节点数介于 11000 之间。
  • 每个节点的值介于 110 ^ 9 之间。
lightbulb

解题思路

方法一

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
46
47
48
49
50
51
52
53
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode recoverFromPreorder(String traversal) {
        Stack<TreeNode> stack = new Stack<>();
        int i = 0;

        while (i < traversal.length()) {
            int depth = 0;
            while (i < traversal.length() && traversal.charAt(i) == '-') {
                depth++;
                i++;
            }

            int num = 0;
            while (i < traversal.length() && Character.isDigit(traversal.charAt(i))) {
                num = num * 10 + (traversal.charAt(i) - '0');
                i++;
            }

            // Create the new node
            TreeNode newNode = new TreeNode(num);

            while (stack.size() > depth) {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                if (stack.peek().left == null) {
                    stack.peek().left = newNode;
                } else {
                    stack.peek().right = newNode;
                }
            }

            stack.push(newNode);
        }
        return stack.isEmpty() ? null : stack.get(0);
    }
}
speed

复杂度分析

指标
时间complexity is O(n) because we parse each character and node once. Space complexity is O(n) due to the stack holding up to all nodes along a path, which is essential to reconstruct the tree correctly.
空间O(n)
psychology

面试官常问的追问

外企场景
  • question_mark

    Ask if the candidate handles single-child nodes correctly as left children.

  • question_mark

    Check if the solution correctly counts dashes to determine node depth.

  • question_mark

    Watch for proper use of a stack or similar structure to maintain current ancestors.

warning

常见陷阱

外企场景
  • error

    Miscounting dashes and attaching nodes to the wrong parent depth.

  • error

    Assuming right children when a node has only one child, breaking tree structure.

  • error

    Pushing all nodes onto the stack without popping ancestors, leading to incorrect hierarchy.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Recover tree from a preorder string with variable-length integers and missing children indicated explicitly.

  • arrow_right_alt

    Construct a tree from a preorder sequence where some nodes may be skipped or null explicitly.

  • arrow_right_alt

    Recover a binary tree while returning the result as a nested dictionary instead of array representation.

help

常见问题

外企场景

从先序遍历还原二叉树题解:二分·树·traversal | LeetCode #1028 困难