Re: [閒聊] 每日leetcode

作者: JIWP (JIWP)   2024-07-15 21:32:43
2196. Create Binary Tree From Descriptions
給一個descriptions矩陣
descriptions[i]=[parent_i,child_i,isLeft_i]
isLeft_i=1代表這是左節點
請根據以上訊息,重組出binary tree
思路:
建立兩個hash table
一個紀錄node,另外一個紀錄node是不是子節點
接著就去建立binary tree
最後回傳父節點就好
滿簡單的一題
golang code :
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func createBinaryTree(descriptions [][]int) *TreeNode {
node,rec:=make(map[int]*TreeNode),make(map[int]byte)
for _,val:=range descriptions{
var parent,child *TreeNode
if _,ok:=node[val[0]];!ok{
parent=&TreeNode{Val:val[0]}
node[val[0]]=parent
}else{
parent=node[val[0]]
}
if _,ok:=node[val[1]];!ok{
child=&TreeNode{Val:val[1]}
node[val[1]]=child
}else{
child=node[val[1]]
}
if val[2]==1{
parent.Left=child
}else{
parent.Right=child
}
rec[val[1]]++
}
for key,val:=range node{
if rec[key]==0{
return val
}
}
return nil
}
作者: oin1104 (是oin的說)   2024-07-15 21:33:00
大師 你發薪水 送我模型
作者: aioiwer318 (哀歐)   2024-07-15 21:33:00
別卷了
作者: DJYOMIYAHINA (通通打死)   2024-07-15 21:37:00
別捲了

Links booklink

Contact Us: admin [ a t ] ucptt.com