Meta 面试题 #6 —— 二叉树按列从左到右遍历(列内自上而下)

1次阅读
没有评论

Given the root of a binary tree containing integers, return a list of all the integers in the tree ordered by column from left to right. Within each column, values should be ordered from top to bottom.

Assume a node definition (or language equivalent):

struct Node {
  Node *left;
  Node *right;
  int val;
};

Input (example, ASCII tree):

      6
     / \
    3   4
   / \ / \
  5  1 7  0
   \    /
    2  8
   / \
  9   7

Output (example):

[5, 9, 3, 2, 6, 1, 7, 4, 8, 0]

总结(含思路):
对每个节点记录列坐标 col(根为 0,左 -1,右 +1)、层 row;用哈希表 col -> list(row,val) 收集,最终按 col 从小到大排序,列内按 row 从小到大输出并拼接。时间 O(n log n)(排序列 / 列内),空间 O(n)。

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 OpenAI、Google、Amazon、Citadel、SIG 等,提供实时答案助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Stripe 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0