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

Binary Tree Level Order Traversal II

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

תיאור השאלה

Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values: level by level from the leaves up to the root, each level from left to right.

איך פותרים?

עושים BFS רגיל לפי רמות, בדיוק כמו בשאלה 102, ובסוף הופכים את סדר הרמות. סיבוכיות: O(n).

פתרון קוד

JavaScript
Python
function levelOrderBottom(root) {
  if (!root) return [];
  const result = [];
  let queue = [root];
  while (queue.length) {
    result.push(queue.map((node) => node.val));
    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.reverse();
}
Book Cover

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

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

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