TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.43K subscribers
Post #1129 870
Задача: 536. Construct Binary Tree from String
Сложность: medium

Вам нужно построить бинарное дерево из строки, состоящей из круглых скобок и целых чисел.

Весь ввод представляет собой бинарное дерево. Он содержит целое число, за которым следуют ноль, одна или две пары круглых скобок. Целое число представляет значение корня, а пара круглых скобок содержит дочернее бинарное дерево с той же структурой.

Вы всегда начинаете строить левый дочерний узел родителя сначала, если он существует.

Пример:
Input: s = "4(2(3)(1))(6(5))"
Output: [4,2,6,3,1,5]


👨‍💻 Алгоритм:

1⃣ Извлечение числа:
Определите функцию getNumber, которая извлекает целое число из текущей строки, начиная с указанного индекса. Учтите знак числа, если он есть.

2⃣ Построение поддерева:
Определите рекурсивную функцию str2treeInternal, которая принимает строку и текущий индекс в качестве входных данных и возвращает пару: узел TreeNode и следующий индекс для обработки.
Внутри функции извлеките значение для корневого узла текущего поддерева, создайте узел, а затем рекурсивно постройте левое и правое поддеревья, если они существуют.

3⃣ Основная функция:
Определите основную функцию str2tree, которая вызывает рекурсивную функцию str2treeInternal и возвращает построенное дерево.

😎 Решение:
class Solution {
public TreeNode str2tree(String s) {
return this.str2treeInternal(s, 0).getKey();
}

public Pair<Integer, Integer> getNumber(String s, int index) {

boolean isNegative = false;

if (s.charAt(index) == '-') {
isNegative = true;
index++;
}

int number = 0;
while (index < s.length() && Character.isDigit(s.charAt(index))) {
number = number * 10 + (s.charAt(index) - '0');
index++;
}

return new Pair<Integer, Integer>(isNegative ? -number : number, index);
}

public Pair<TreeNode, Integer> str2treeInternal(String s, int index) {

if (index == s.length()) {
return new Pair<TreeNode, Integer>(null, index);
}

Pair<Integer, Integer> numberData = this.getNumber(s, index);
int value = numberData.getKey();
index = numberData.getValue();

TreeNode node = new TreeNode(value);
Pair<TreeNode, Integer> data;

if (index < s.length() && s.charAt(index) == '(') {
data = this.str2treeInternal(s, index + 1);
node.left = data.getKey();
index = data.getValue();
}

if (node.left != null && index < s.length() && s.charAt(index) == '(') {
data = this.str2treeInternal(s, index + 1);
node.right = data.getKey();
index = data.getValue();
}

return new Pair<TreeNode, Integer>(node, index < s.length() && s.charAt(index) == ')' ? index + 1 : index);
}
}


Ставь 👍 и забирай 📚 Базу знаний
  • 💊 1
More from @easy_java_task
  1. Oct 18, 2026Post #2305
  2. Oct 17, 2026Задача: 745. Prefix and Suffix Search Сложность: hard Создайте специальный словарь, в кото…
  3. Oct 17, 2026Post #2303
  4. Oct 17, 2026Задача: 1431. Kids With the Greatest Number of Candies Сложность: easy Дано n детей с конф…
  5. Oct 16, 2026Задача: 735. Asteroid Collision Сложность: medium Нам дан массив asteroids, состоящий из ц…
  6. Oct 15, 2026Задача: 229. Majority Element II Сложность: medium Дан массив целых чисел размера n, найди…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →