hello-algo/codes/swift/chapter_divide_and_conquer/build_tree.swift
2023-09-15 02:08:09 +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], 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: 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)
}
}