All files / leetCode 0105.ts

100% Statements 7/7
100% Branches 2/2
100% Functions 1/1
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25            14x 8x   6x 6x   6x         6x         6x    
import { TreeNode } from './Tree'
 
export default function buildTree(
  preorder: number[],
  inorder: number[],
): TreeNode<number> | null {
  if (preorder.length === 0)
    return null
 
  const root = new TreeNode(preorder[0])
  const preorderIndex = inorder.indexOf(preorder[0])
 
  root.left = buildTree(
    preorder.slice(1, preorderIndex + 1),
    inorder.slice(0, preorderIndex),
  )
 
  root.right = buildTree(
    preorder.slice(preorderIndex + 1),
    inorder.slice(preorderIndex + 1),
  )
 
  return root
}