0x00 题目
根据一棵树的 中序
遍历与 后序
遍历构造二叉树
注意:
你可以假设树中 没有
重复的元素
0x01 思路
对于 后序
遍历,最后一个
元素必为根
只要找到 最后一个
元素在中序遍历中的 位置
就可以将数组一分为二,
左侧
为 左子树
的遍历结果,右侧
为 右子树
对拆分后的两个数组 递归
的进行上述操作即可
0x02 解法
语言:Swift
树节点:TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
解法:
func buildTree(_ inorder: [Int], _ postorder: [Int]) -> TreeNode? {
var dict: [Int: Int] = [:]
// 中序遍历,值对应的索引
for i in 0..<inorder.count {
dict[inorder[i]] = i
}
func build(_ inorder: [Int], _ inStart: Int, _ inEnd: Int, _ postorder: [Int], _ postStart: Int, _ postEnd: Int) -> TreeNode? {
if inStart > inEnd || postStart > postEnd { return nil }
// 根节点
let val = postorder[postEnd]
let root = TreeNode(val)
// 根节点索引
let index = dict[val]!
// 左子树长度
let leftSize = index - inStart
// 构建左子树
root.left = build(inorder, inStart, index-1,
postorder, postStart, postStart+leftSize-1)
// 构建右子树
root.right = build(inorder, index+1, inEnd,
postorder, postStart+leftSize, postEnd-1)
return root
}
let node = build(inorder, 0, inorder.count-1, postorder, 0, postorder.count-1)
return node
}
小编辑器
App Store 搜索即可。