hello-algo/codes/swift/chapter_divide_and_conquer/build_tree.swift
nuomi1 b6ac6aa7d7
Feature/chapter divide and conquer swift (#719)
* feat: add Swift codes for binary_search_recur article

* feat: add Swift codes for build_binary_tree_problem article

* feat: add Swift codes for hanota_problem article
2023-09-02 23:08:37 +08:00

47 lines
1.5 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: build_tree.swift
* Created Time: 2023-09-02
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
func dfs(preorder: [Int], inorder: [Int], hmap: [Int: Int], i: Int, l: Int, r: Int) -> TreeNode? {
//
if r - l < 0 {
return nil
}
//
let root = TreeNode(x: preorder[i])
// m
let m = hmap[preorder[i]]!
//
root.left = dfs(preorder: preorder, inorder: inorder, hmap: hmap, i: i + 1, l: l, r: m - 1)
//
root.right = dfs(preorder: preorder, inorder: inorder, hmap: hmap, i: i + 1 + m - l, l: m + 1, r: r)
//
return root
}
/* */
func buildTree(preorder: [Int], inorder: [Int]) -> TreeNode? {
// inorder
let hmap = inorder.enumerated().reduce(into: [:]) { $0[$1.element] = $1.offset }
return dfs(preorder: preorder, inorder: inorder, hmap: hmap, i: 0, l: 0, r: inorder.count - 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)
}
}