The code could might feel huge, but my only doubt is in the function find()
inside the if statement root == null
See if root == null
is true, then the find
function must return false
right?
But what happens according to debugging is:
Only should print once BUT it print multiple times (!?) --> null Only should print once BUT it print multiple times (!?) --> null Only should print once and it prints one time only as expected! result true
The important part in the above println logs is Only should print once BUT it print multiple times (!?) --> null
is root == null
is true and we are entering the if
block, so the function find()
at once MUST return true
and exit right?
But what happens it, the code is seemingly ignoring that and not returning false
!! and here is where I am confused!
Code below:
“`kotlin
class TwoSumIV {
class TreeNode(var `val`: Int = 0) { var left: TreeNode? = null var right: TreeNode? = null } fun findTarget(root: TreeNode?, k: Int): Boolean { val set: MutableSet<Int?> = HashSet<Int?>() return find(root, k, set) } fun find(root: TreeNode?, k: Int, set: MutableSet<Int?>): Boolean { if (root == null) { println("Only should print once BUT it print multiple times (!?) --> ${root?.`val`}") return false } else if (set.contains(k - root.`val`)) { println("Only should print once and it prints one time only as expected!") return true } set.add(root.`val`) return find(root.left, k, set) || find(root.right, k, set) }
}
fun main() { val root = TwoSumIV.TreeNode(5) root.left = TwoSumIV.TreeNode(3) root.right = TwoSumIV.TreeNode(6)
println(root) val twoSumIV = TwoSumIV() val result = twoSumIV.findTarget(root, 9) println("result $result")
} “`
submitted by /u/Kaori_iu
[link] [comments]