Re: [閒聊] 每日leetcode已回收
這題好像沒什麼好講的,不過我需要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
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.71.214.211 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1715953828.A.83F.html
推
05/17 21:51,
1年前
, 1F
05/17 21:51, 1F
推
05/17 21:51,
1年前
, 2F
05/17 21:51, 2F
推
05/17 21:52,
1年前
, 3F
05/17 21:52, 3F
討論串 (同標題文章)
完整討論串 (本文為第 235 之 1554 篇):