Created
April 14, 2020 06:48
-
-
Save Chesteer89/9cb248ef6c677f4f31958f0836f41957 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data class Tree<T>(var value: T) { | |
var left: Tree<T>? = null | |
var right: Tree<T>? = null | |
} | |
fun constructSumTree(tree: Tree<Int>?): Tree<Int>? { | |
if(tree == null) return null | |
reduceLeafs(tree) | |
return tree | |
} | |
fun reduceLeafs(tree: Tree<Int>): Int { | |
with(tree){ | |
if(left == null && right == null) { | |
println("Leafs reached") | |
val temp = value | |
value = 0 | |
return temp | |
} | |
val leftValue = if(left == null) 0 else reduceLeafs(left!!) | |
val rightValue = if(right == null) 0 else reduceLeafs(right!!) | |
value += leftValue + rightValue | |
println("New value set to value") | |
return value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment