作者JIWP (神楽めあ的錢包)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Mon Jul 15 21:32:43 2024
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
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.71.212.30 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1721050365.A.7F9.html
推 oin1104: 大師 你發薪水 送我模型 07/15 21:33
推 aioiwer318: 別卷了 07/15 21:33
推 DJYOMIYAHINA: 別捲了 07/15 21:37