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