Last active
March 6, 2023 14:15
-
-
Save kaiqkt/a7826439a9d54041317e14e33302271a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import java.io.PrintStream | |
class Node( | |
val value: Int, | |
var left: Node? = null, | |
var right: Node? = null | |
) { | |
override fun toString(): String { | |
return "Node(value=$value, left=$left, right=$right)" | |
} | |
} | |
class BinaryTree { | |
private var root: Node? = null | |
fun add(value: Int) { | |
root = recursive(root, value) | |
} | |
private fun recursive(current: Node?, value: Int): Node { | |
if (current == null) { | |
return Node(value) | |
} | |
if (value < current.value) { | |
current.left = recursive(current.left, value) | |
} else if (value > current.value) { | |
current.right = recursive(current.right, value) | |
} else { | |
return current | |
} | |
return current | |
} | |
fun leafSum(): Int { | |
return leftLeavesSum(root) | |
} | |
private fun isLeaf(node: Node?): Boolean { | |
if (node == null) | |
return false | |
return node.left == null && node.right == null | |
} | |
private fun leftLeavesSum(node: Node?): Int { | |
var res = 0 | |
if (node != null) { | |
if (isLeaf(node.left)) | |
res += node.left!!.value | |
else | |
res += leftLeavesSum(node.left) | |
res += leftLeavesSum(node.right) | |
} | |
return res | |
} | |
private fun traversePreOrder(sb: StringBuilder, padding: String?, pointer: String?, node: Node?) { | |
if (node != null) { | |
sb.append(padding) | |
sb.append(pointer) | |
sb.append(node.value) | |
sb.append("\n") | |
val paddingBuilder = StringBuilder(padding) | |
paddingBuilder.append("│ ") | |
val paddingForBoth = paddingBuilder.toString() | |
val pointerForRight = "└──" | |
val pointerForLeft = if (node.right != null) "├──" else "└──" | |
traversePreOrder(sb, paddingForBoth, pointerForLeft, node.left) | |
traversePreOrder(sb, paddingForBoth, pointerForRight, node.right) | |
} | |
} | |
fun print(os: PrintStream) { | |
val sb = StringBuilder() | |
traversePreOrder(sb, "", "", this.root) | |
os.print(sb.toString()) | |
} | |
} | |
fun main() { | |
val bt = BinaryTree() | |
bt.add(20) | |
bt.add(9) | |
bt.add(49) | |
bt.add(23) | |
bt.add(52) | |
bt.add(15) | |
bt.add(7) | |
println(bt.print(System.out)) | |
println(bt.leafSum()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment