You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_divide_and_conquer/build_tree.swift

48 lines
1.5 KiB

/**
* File: build_tree.swift
* Created Time: 2023-09-02
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
func dfs(preorder: [Int], inorderMap: [Int: Int], i: Int, l: Int, r: Int) -> TreeNode? {
//
if r - l < 0 {
return nil
}
//
let root = TreeNode(x: preorder[i])
// m
let m = inorderMap[preorder[i]]!
//
root.left = dfs(preorder: preorder, inorderMap: inorderMap, i: i + 1, l: l, r: m - 1)
//
root.right = dfs(preorder: preorder, inorderMap: inorderMap, i: i + 1 + m - l, l: m + 1, r: r)
//
return root
}
/* */
func buildTree(preorder: [Int], inorder: [Int]) -> TreeNode? {
// inorder
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("前序遍历 = \(preorder)")
print("中序遍历 = \(inorder)")
let root = buildTree(preorder: preorder, inorder: inorder)
print("构建的二叉树为:")
PrintUtil.printTree(root: root)
}
}