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

Binary Tree Zigzag Level Order Traversal

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

תיאור השאלה

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values: the first level from left to right, the next from right to left, and so on, alternating.

איך פותרים?

אותו BFS כמו במעבר לפי רמות, עם דגל שמתחלף בכל רמה. ברמות האי־זוגיות הופכים את רשימת הערכים לפני שמוסיפים אותה לתוצאה. סיבוכיות: O(n).

פתרון קוד

JavaScript
Python
function zigzagLevelOrder(root) {
  if (!root) return [];
  const result = [];
  let queue = [root];
  let leftToRight = true;
  while (queue.length) {
    const level = queue.map((node) => node.val);
    result.push(leftToRight ? level : level.reverse());
    leftToRight = !leftToRight;
    const next = [];
    for (const node of queue) {
      if (node.left) next.push(node.left);
      if (node.right) next.push(node.right);
    }
    queue = next;
  }
  return result;
}
Book Cover

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

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

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