mirror of
https://github.com/krahets/hello-algo.git
synced 2026-07-09 14:06:06 +00:00
2778a6f9c7
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
48 lines
1.6 KiB
Swift
48 lines
1.6 KiB
Swift
/**
|
|
* File: build_tree.swift
|
|
* Created Time: 2023-09-02
|
|
* Author: nuomi1 (nuomi1@qq.com)
|
|
*/
|
|
|
|
import utils
|
|
|
|
/* Build binary tree: divide and conquer */
|
|
func dfs(preorder: [Int], inorderMap: [Int: Int], i: Int, l: Int, r: Int) -> TreeNode? {
|
|
// Terminate when the subtree interval is empty
|
|
if r - l < 0 {
|
|
return nil
|
|
}
|
|
// Initialize the root node
|
|
let root = TreeNode(x: preorder[i])
|
|
// Query m to divide the left and right subtrees
|
|
let m = inorderMap[preorder[i]]!
|
|
// Subproblem: build the left subtree
|
|
root.left = dfs(preorder: preorder, inorderMap: inorderMap, i: i + 1, l: l, r: m - 1)
|
|
// Subproblem: build the right subtree
|
|
root.right = dfs(preorder: preorder, inorderMap: inorderMap, i: i + 1 + m - l, l: m + 1, r: r)
|
|
// Return the root node
|
|
return root
|
|
}
|
|
|
|
/* Build binary tree */
|
|
func buildTree(preorder: [Int], inorder: [Int]) -> TreeNode? {
|
|
// Initialize hash map, storing the mapping from inorder elements to indices
|
|
let inorderMap = inorder.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset }
|
|
return dfs(preorder: preorder, inorderMap: inorderMap, i: inorder.startIndex, l: inorder.startIndex, r: inorder.endIndex - 1)
|
|
}
|
|
|
|
@main
|
|
enum BuildTree {
|
|
/* Driver Code */
|
|
static func main() {
|
|
let preorder = [3, 9, 2, 1, 7]
|
|
let inorder = [9, 3, 1, 2, 7]
|
|
print("Pre-order traversal = \(preorder)")
|
|
print("In-order traversal = \(inorder)")
|
|
|
|
let root = buildTree(preorder: preorder, inorder: inorder)
|
|
print("The constructed binary tree is:")
|
|
PrintUtil.printTree(root: root)
|
|
}
|
|
}
|