Re: [闲聊] 每日leetcode

楼主: JIWP (JIWP)   2024-05-17 21:50:26
这题好像没什么好讲的,不过我需要p币
让我片一下p币
1325. Delete Leaves With a Given Value
有一棵二元树
给你一个target value
如果叶子节点的value跟target相等则删除该叶子节点
如果一个父节点因为上述的操作变成叶子节点,且value=target
那也要删掉
请回传进行上述动作后的二元树
思路:
没什么好讲的,就dfs
先处理左、右子节点
再来看父节点是不是也要删除
golang code :
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func removeLeafNodes(root *TreeNode, target int) *TreeNode {
if root==nil{
return root
}
root.Left=removeLeafNodes(root.Left,target)
root.Right=removeLeafNodes(root.Right,target)
if root.Left==nil && root.Right==nil && root.Val==target{
return nil
}
return root
}
作者: aioiwer318 (哀欧)   2024-05-17 21:51:00
别卷了
作者: oinishere (是oin捏)   2024-05-17 21:51:00
内推我
作者: sustainer123 (caster)   2024-05-17 21:52:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com