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