问题:
![]()
方法:
基于树的递归,但是需要回溯当前结点,最后一直回溯到根节点,如果当前结点是叶子结点同时等于target时回溯时返回null否则返回当前结点,最后就能得到正确的结果。
class DeleteLeavesWithAGivenValue {
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun removeLeafNodes(root: TreeNode?, target: Int): TreeNode? {
if (root == null) {
return root
}
return dfs(root, target)
}
private fun dfs(root: TreeNode, target: Int): TreeNode? {
root.left = root.left?.let { dfs(it, target) }
root.right = root.right?.let { dfs(it, target) }
if (root.left == null && root.right == null && root.`val` == target) {
return null
}
return root
}
}
有问题随时沟通
网友评论