תיאור השאלה
Given an integer n, return all structurally unique binary search trees that have exactly n nodes with unique values from 1 to n. The answer can be in any order.
איך פותרים?
רקורסיה על טווח [start, end]: כל מספר i בטווח יכול להיות השורש. בונים את כל תתי־העצים השמאליים מ־[start, i-1] ואת כל הימניים מ־[i+1, end], ומחברים כל זוג לשורש חדש. טווח ריק מחזיר רשימה עם null.
פתרון קוד
JavaScript
Python
function generateTrees(n) {
function build(start, end) {
if (start > end) return [null];
const trees = [];
for (let i = start; i <= end; i++) {
for (const left of build(start, i - 1)) {
for (const right of build(i + 1, end)) {
trees.push(new TreeNode(i, left, right));
}
}
}
return trees;
}
return build(1, n);
}
לעבור את ראיון העבודה הבא שלך בהצלחה
קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.