7373
7474<!-- solution:start -->
7575
76- ### 方法一
76+ ### 方法一:哈希表
77+
78+ 我们可以用一个哈希表 $\textit{nodes}$ 来存储所有节点,其中键为节点的值,值为节点本身,用一个集合 $\textit{children}$ 来存储所有的子节点。
79+
80+ 遍历 $\textit{descriptions}$,对于每个描述 $[ \textit{parent}, \textit{child}, \textit{isLeft}] $,如果 $\textit{parent}$ 不在 $\textit{nodes}$ 中,我们就将 $\textit{parent}$ 加入 $\textit{nodes}$,并初始化一个值为 $\textit{parent}$ 的节点。如果 $\textit{child}$ 不在 $\textit{nodes}$ 中,我们就将 $\textit{child}$ 加入 $\textit{nodes}$,并初始化一个值为 $\textit{child}$ 的节点。然后我们将 $\textit{child}$ 加入 $\textit{children}$。
81+
82+ 如果 $\textit{isLeft}$ 为真,我们就将 $\textit{child}$ 作为 $\textit{parent}$ 的左子节点,否则我们就将 $\textit{child}$ 作为 $\textit{parent}$ 的右子节点。
83+
84+ 最后,我们遍历 $\textit{nodes}$,如果某个节点的值不在 $\textit{children}$ 中,那么这个节点就是根节点,我们返回这个节点。
85+
86+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 是 $\textit{descriptions}$ 的长度。
7787
7888<!-- tabs:start -->
7989
@@ -88,21 +98,20 @@ tags:
8898# self.right = right
8999class Solution :
90100 def createBinaryTree (self , descriptions : List[List[int ]]) -> Optional[TreeNode]:
91- g = defaultdict(TreeNode)
92- vis = set ()
93- for p, c, left in descriptions:
94- if p not in g:
95- g[p] = TreeNode(p)
96- if c not in g:
97- g[c] = TreeNode(c)
98- if left:
99- g[p].left = g[c]
101+ nodes = defaultdict(TreeNode)
102+ children = set ()
103+ for parent, child, isLeft in descriptions:
104+ if parent not in nodes:
105+ nodes[parent] = TreeNode(parent)
106+ if child not in nodes:
107+ nodes[child] = TreeNode(child)
108+ children.add(child)
109+ if isLeft:
110+ nodes[parent].left = nodes[child]
100111 else :
101- g[p].right = g[c]
102- vis.add(c)
103- for v, node in g.items():
104- if v not in vis:
105- return node
112+ nodes[parent].right = nodes[child]
113+ root = (set (nodes.keys()) - children).pop()
114+ return nodes[root]
106115```
107116
108117#### Java
@@ -125,26 +134,26 @@ class Solution:
125134 */
126135class Solution {
127136 public TreeNode createBinaryTree (int [][] descriptions ) {
128- Map<Integer , TreeNode > m = new HashMap<> ();
129- Set<Integer > vis = new HashSet<> ();
130- for (int [] d : descriptions) {
131- int p = d[0 ], c = d[1 ], isLeft = d[2 ];
132- if (! m . containsKey(p )) {
133- m . put(p , new TreeNode (p ));
137+ Map<Integer , TreeNode > nodes = new HashMap<> ();
138+ Set<Integer > children = new HashSet<> ();
139+ for (var d : descriptions) {
140+ int parent = d[0 ], child = d[1 ], isLeft = d[2 ];
141+ if (! nodes . containsKey(parent )) {
142+ nodes . put(parent , new TreeNode (parent ));
134143 }
135- if (! m . containsKey(c )) {
136- m . put(c , new TreeNode (c ));
144+ if (! nodes . containsKey(child )) {
145+ nodes . put(child , new TreeNode (child ));
137146 }
138147 if (isLeft == 1 ) {
139- m . get(p ). left = m . get(c );
148+ nodes . get(parent ). left = nodes . get(child );
140149 } else {
141- m . get(p ). right = m . get(c );
150+ nodes . get(parent ). right = nodes . get(child );
142151 }
143- vis . add(c );
152+ children . add(child );
144153 }
145- for (Map . Entry< Integer , TreeNode > entry : m . entrySet()) {
146- if (! vis . contains(entry . getKey())) {
147- return entry . getValue();
154+ for (var e : nodes . entrySet()) {
155+ if (! children . contains(e . getKey())) {
156+ return e . getValue();
148157 }
149158 }
150159 return null ;
@@ -169,20 +178,27 @@ class Solution {
169178class Solution {
170179public:
171180 TreeNode* createBinaryTree(vector<vector<int >>& descriptions) {
172- unordered_map<int, TreeNode* > m;
173- unordered_set<int > vis;
174- for (auto& d : descriptions) {
175- int p = d[ 0] , c = d[ 1] , left = d[ 2] ;
176- if (!m.count(p)) m[ p] = new TreeNode(p);
177- if (!m.count(c)) m[ c] = new TreeNode(c);
178- if (left)
179- m[ p] ->left = m[ c] ;
180- else
181- m[ p] ->right = m[ c] ;
182- vis.insert(c);
181+ unordered_map<int, TreeNode* > nodes;
182+ unordered_set<int > children;
183+ for (const auto& d : descriptions) {
184+ int parent = d[ 0] , child = d[ 1] , isLeft = d[ 2] ;
185+ if (!nodes.contains(parent)) {
186+ nodes[ parent] = new TreeNode(parent);
187+ }
188+ if (!nodes.contains(child)) {
189+ nodes[ child] = new TreeNode(child);
190+ }
191+ if (isLeft) {
192+ nodes[ parent] ->left = nodes[ child] ;
193+ } else {
194+ nodes[ parent] ->right = nodes[ child] ;
195+ }
196+ children.insert(child);
183197 }
184- for (auto& [ v, node] : m) {
185- if (!vis.count(v)) return node;
198+ for (const auto& [ k, v] : nodes) {
199+ if (!children.contains(k)) {
200+ return v;
201+ }
186202 }
187203 return nullptr;
188204 }
@@ -201,27 +217,26 @@ public:
201217 * }
202218 */
203219func createBinaryTree(descriptions [][]int) *TreeNode {
204- m := make( map[int]*TreeNode)
205- vis := make( map[int]bool)
220+ nodes := map[int]*TreeNode{}
221+ children := map[int]bool{}
206222 for _, d := range descriptions {
207- p, c, left := d[0], d[1], d[2]
208- if m[p] == nil {
209- m[p ] = &TreeNode{Val: p }
223+ parent, child, isLeft := d[0], d[1], d[2]
224+ if _, ok := nodes[parent]; !ok {
225+ nodes[parent ] = &TreeNode{Val: parent }
210226 }
211- if m[c] == nil {
212- m[c ] = &TreeNode{Val: c }
227+ if _, ok := nodes[child]; !ok {
228+ nodes[child ] = &TreeNode{Val: child }
213229 }
214- if left == 1 {
215- m[p ].Left = m[c ]
230+ if isLeft == 1 {
231+ nodes[parent ].Left = nodes[child ]
216232 } else {
217- m[p ].Right = m[c ]
233+ nodes[parent ].Right = nodes[child ]
218234 }
219- vis[c ] = true
235+ children[child ] = true
220236 }
221-
222- for v, node := range m {
223- if !vis[v] {
224- return node
237+ for k, v := range nodes {
238+ if _, ok := children[k]; !ok {
239+ return v
225240 }
226241 }
227242 return nil
@@ -248,63 +263,26 @@ func createBinaryTree(descriptions [][]int) *TreeNode {
248263function createBinaryTree(descriptions : number [][]): TreeNode | null {
249264 const nodes: Record <number , TreeNode > = {};
250265 const children = new Set <number >();
251-
252- for (const [parent, child] of descriptions ) {
253- if (! nodes [parent ]) nodes [parent ] = new TreeNode (parent );
254- if (! nodes [child ]) nodes [child ] = new TreeNode (child );
255-
256- children .add (child );
257- }
258-
259- let root = - 1 ;
260266 for (const [parent, child, isLeft] of descriptions ) {
261- if (! children .has (parent )) root = parent ;
262-
263- if (isLeft ) nodes [parent ].left = nodes [child ];
264- else nodes [parent ].right = nodes [child ];
265- }
266-
267- return nodes [root ];
268- }
269- ```
270-
271- #### JavaScript
272-
273- ``` js
274- /**
275- * Definition for a binary tree node.
276- * function TreeNode(val, left, right) {
277- * this.val = (val===undefined ? 0 : val)
278- * this.left = (left===undefined ? null : left)
279- * this.right = (right===undefined ? null : right)
280- * }
281- */
282- /**
283- * @param {number[][]} descriptions
284- * @return {TreeNode}
285- */
286-
287- var createBinaryTree = function (descriptions ) {
288- const nodes = {};
289- const children = new Set ();
290-
291- for (const [parent , child ] of descriptions) {
292- if (! nodes[parent]) nodes[parent] = new TreeNode (parent);
293- if (! nodes[child]) nodes[child] = new TreeNode (child);
294-
267+ if (! nodes [parent ]) {
268+ nodes [parent ] = new TreeNode (parent );
269+ }
270+ if (! nodes [child ]) {
271+ nodes [child ] = new TreeNode (child );
272+ }
273+ if (isLeft ) {
274+ nodes [parent ].left = nodes [child ];
275+ } else {
276+ nodes [parent ].right = nodes [child ];
277+ }
295278 children .add (child );
296279 }
297-
298- let root = - 1 ;
299- for (const [parent , child , isLeft ] of descriptions) {
300- if (! children .has (parent)) root = parent;
301-
302- if (isLeft) nodes[parent].left = nodes[child];
303- else nodes[parent].right = nodes[child];
280+ for (const [k, v] of Object .entries (nodes )) {
281+ if (! children .has (+ k )) {
282+ return v ;
283+ }
304284 }
305-
306- return nodes[root];
307- };
285+ }
308286```
309287
310288#### Rust
@@ -329,49 +307,87 @@ var createBinaryTree = function (descriptions) {
329307// }
330308// }
331309use std :: cell :: RefCell ;
332- use std :: collections :: HashMap ;
310+ use std :: collections :: { HashMap , HashSet } ;
333311use std :: rc :: Rc ;
334312impl Solution {
335- fn dfs (val : i32 , map : & HashMap <i32 , [i32 ; 2 ]>) -> Option <Rc <RefCell <TreeNode >>> {
336- if val == 0 {
337- return None ;
338- }
339- let mut left = None ;
340- let mut right = None ;
341- if let Some (& [l_val , r_val ]) = map . get (& val ) {
342- left = Self :: dfs (l_val , map );
343- right = Self :: dfs (r_val , map );
344- }
345- Some (Rc :: new (RefCell :: new (TreeNode { val , left , right })))
346- }
347-
348313 pub fn create_binary_tree (descriptions : Vec <Vec <i32 >>) -> Option <Rc <RefCell <TreeNode >>> {
349- let mut map = HashMap :: new ();
350- let mut is_root = HashMap :: new ();
351- for description in descriptions . iter () {
352- let (parent , child , is_left ) = (description [0 ], description [1 ], description [2 ] == 1 );
353- let [mut left , mut right ] = map . get (& parent ). unwrap_or (& [0 , 0 ]);
354- if is_left {
355- left = child ;
314+ let mut nodes = HashMap :: new ();
315+ let mut children = HashSet :: new ();
316+
317+ for d in descriptions {
318+ let parent = d [0 ];
319+ let child = d [1 ];
320+ let is_left = d [2 ];
321+
322+ nodes
323+ . entry (parent )
324+ . or_insert_with (|| Rc :: new (RefCell :: new (TreeNode :: new (parent ))));
325+ nodes
326+ . entry (child )
327+ . or_insert_with (|| Rc :: new (RefCell :: new (TreeNode :: new (child ))));
328+
329+ if is_left == 1 {
330+ nodes . get (& parent ). unwrap (). borrow_mut (). left =
331+ Some (Rc :: clone (nodes . get (& child ). unwrap ()));
356332 } else {
357- right = child ;
333+ nodes . get (& parent ). unwrap (). borrow_mut (). right =
334+ Some (Rc :: clone (nodes . get (& child ). unwrap ()));
358335 }
359- if ! is_root . contains_key (& parent ) {
360- is_root . insert (parent , true );
361- }
362- is_root . insert (child , false );
363- map . insert (parent , [left , right ]);
336+
337+ children . insert (child );
364338 }
365- for key in is_root . keys () {
366- if * is_root . get (key ). unwrap () {
367- return Self :: dfs (* key , & map );
339+
340+ for (key , node ) in & nodes {
341+ if ! children . contains (key ) {
342+ return Some (Rc :: clone (node ));
368343 }
369344 }
345+
370346 None
371347 }
372348}
373349```
374350
351+ #### JavaScript
352+
353+ ``` js
354+ /**
355+ * Definition for a binary tree node.
356+ * function TreeNode(val, left, right) {
357+ * this.val = (val===undefined ? 0 : val)
358+ * this.left = (left===undefined ? null : left)
359+ * this.right = (right===undefined ? null : right)
360+ * }
361+ */
362+ /**
363+ * @param {number[][]} descriptions
364+ * @return {TreeNode}
365+ */
366+ var createBinaryTree = function (descriptions ) {
367+ const nodes = {};
368+ const children = new Set ();
369+ for (const [parent , child , isLeft ] of descriptions) {
370+ if (! nodes[parent]) {
371+ nodes[parent] = new TreeNode (parent);
372+ }
373+ if (! nodes[child]) {
374+ nodes[child] = new TreeNode (child);
375+ }
376+ if (isLeft) {
377+ nodes[parent].left = nodes[child];
378+ } else {
379+ nodes[parent].right = nodes[child];
380+ }
381+ children .add (child);
382+ }
383+ for (const [k , v ] of Object .entries (nodes)) {
384+ if (! children .has (+ k)) {
385+ return v;
386+ }
387+ }
388+ };
389+ ```
390+
375391<!-- tabs: end -->
376392
377393<!-- solution: end -->
0 commit comments