Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

105. Construct Binary Tree from Preorder and Inorder Traversal

Topics: Array Hash Table Divide and Conquer Tree Binary Tree

Solution

Implementation

class Solution {
    fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
        if (preorder.isEmpty()) return null

        val value = preorder[0]
        val node = TreeNode(value)
        val rootIndex = inorder.indexOf(value)

        node.left = buildTree(
            preorder.copyOfRange(1, rootIndex + 1),
            inorder.copyOfRange(0, rootIndex) 
        )

        node.right = buildTree(
            preorder.copyOfRange(rootIndex + 1, preorder.size),
            inorder.copyOfRange(rootIndex + 1, inorder.size)
        )

        return node 
    }
}