func buildTree(_ preorder: [Int], _ inorder: [Int]) -> TreeNode? {
if preorder.isEmpty {
return nil
}
let node = TreeNode(preorder[0])
let index = inorder.firstIndex(of: preorder[0])!
if index == 0 {
node.left = nil
} else {
node.left = buildTree(Array(preorder[1...index]), Array(inorder[0..<index]))
}
if index == inorder.count - 1 {
node.right = nil
} else {
node.right = buildTree(Array(preorder[(index+1)...]), Array(inorder[(index+1)...]))
}
return node
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme