在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a binary tree root and an integer target, delete all the leaf nodes with value target. Note that once you delete a leaf node with value target, if it's parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you can't).
Example 1:
Input: root = [1,2,3,2,null,2,4], target = 2
Input: root = [1,3,3,3,2], target = 3
Input: root = [1,2,null,2,null,2], target = 2 Input: root = [1,1,1], target = 1 Input: root = [1,2,3], target = 1 Constraints: 1 <= target <= 1000 给你一棵以 root 为根的二叉树和一个整数 target ,请你删除所有值为 target 的 叶子节点 。 注意,一旦删除值为 target 的叶子节点,它的父节点就可能变成叶子节点;如果新叶子节点的值恰好也是 target ,那么这个节点也应该被删除。 也就是说,你需要重复此过程直到不能继续删除。
示例 1:
输入:root = [1,2,3,2,null,2,4], target = 2
输入:root = [1,3,3,3,2], target = 3
输入:root = [1,2,null,2,null,2], target = 2 输入:root = [1,1,1], target = 1 输入:root = [1,2,3], target = 1 提示: 1 <= target <= 1000 Runtime: 40 ms
Memory Usage: 21.3 MB
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func removeLeafNodes(_ root: TreeNode?, _ target: Int) -> TreeNode? { 16 if root == nil {return nil} 17 let left:TreeNode? = removeLeafNodes(root?.left, target) 18 let right:TreeNode? = removeLeafNodes(root?.right, target) 19 if left == nil && right == nil && root?.val == target 20 { 21 return nil 22 } 23 root?.left=left 24 root?.right=right 25 return root 26 } 27 }
|
请发表评论