🤖המדריך להייטיקיסט המתחיל
בינוניLeetCode #116

Populating Next Right Pointers in Each Node

עשויה להישאל ב:MicrosoftAmazonMeta

תיאור השאלה

You are given a perfect binary tree, where all leaves are on the same level and every parent has two children. Populate each node's next pointer to point to its next right node on the same level, or null if there is none.

איך פותרים?

משתמשים במצביעי next שכבר חיברנו ברמה הנוכחית כדי לחבר את הרמה הבאה. לכל צומת: הבן השמאלי מצביע על הבן הימני, והבן הימני מצביע על הבן השמאלי של השכן הבא. בלי תור ובלי זיכרון נוסף. סיבוכיות: O(n) זמן, O(1) זיכרון.

פתרון קוד

JavaScript
Python
function connect(root) {
  let leftmost = root;
  while (leftmost && leftmost.left) {
    let node = leftmost;
    while (node) {
      node.left.next = node.right;
      if (node.next) node.right.next = node.next.left;
      node = node.next;
    }
    leftmost = leftmost.left;
  }
  return root;
}
Book Cover

לעבור את ראיון העבודה הבא שלך בהצלחה

קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.

התחל עכשיו ב-149 ₪ בלבד! 🚀