時間複雜度:O(n),其中 n 是 descriptions 的長度。我們需要遍歷一次 descriptions 來建立節點關係,然後最多再遍歷一次來找到根節點。
空間複雜度:O(n)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defcreateBinaryTree(self, descriptions: List[List[int]]) -> Optional[TreeNode]: mp = {} # val -> TreeNode pa = {} # child -> parent for u, v, is_left in descriptions: pa[v] = u if u notin mp: mp[u] = TreeNode(u) if v notin mp: mp[v] = TreeNode(v) if is_left: mp[u].left = mp[v] else: mp[u].right = mp[v]
root = descriptions[0][0] while root in pa: root = pa[root] return mp[root]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: TreeNode* createBinaryTree(vector<vector<int>>& descriptions){ unordered_map<int, TreeNode*> mp; unordered_map<int, int> pa; for (auto& desc : descriptions) { int u = desc[0], v = desc[1]; bool is_left = desc[2]; pa[v] = u; if (!mp.count(u)) mp[u] = newTreeNode(u); if (!mp.count(v)) mp[v] = newTreeNode(v); if (is_left) mp[u]->left = mp[v]; else mp[u]->right = mp[v]; } int root = descriptions[0][0]; while (pa.count(root)) root = pa[root]; return mp[root]; } };
寫在最後
Cover photo is remixed from @吃肥皂泡泡, thanks for their work!