From 3460ef6dbdd3d4511574eb9d95e9d31afbce516e Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 18 Jan 2022 16:17:04 +0100 Subject: [PATCH] problems: add inorder bst traversal Signed-off-by: Matej Focko --- problems/binary-tree-inorder-traversal.kt | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 problems/binary-tree-inorder-traversal.kt diff --git a/problems/binary-tree-inorder-traversal.kt b/problems/binary-tree-inorder-traversal.kt new file mode 100644 index 0000000..a1013f3 --- /dev/null +++ b/problems/binary-tree-inorder-traversal.kt @@ -0,0 +1,26 @@ +/** + * Example: + * var ti = TreeNode(5) + * var v = ti.`val` + * Definition for a binary tree node. + * class TreeNode(var `val`: Int) { + * var left: TreeNode? = null + * var right: TreeNode? = null + * } + */ +class Solution { + fun inorderTraversal(root: TreeNode?, values: MutableList): List { + if (root == null) { + return values + } + + inorderTraversal(root.left, values) + values.add(root.`val`!!) + inorderTraversal(root.right, values) + + return values + } + + fun inorderTraversal(root: TreeNode?): List + = inorderTraversal(root, mutableListOf()) +}