根据中序、后序还原二叉树
简介
给定二叉树的中序遍历和后序遍历序列,可以还原出原始的二叉树。中序遍历是先遍历左子树,然后访问根节点,最后遍历右子树。后序遍历是先遍历左子树,然后遍历右子树,最后访问根节点。
二叉树
示例
中序遍历序列:['d', 'b', 'e', 'a', 'f', 'c', 'g']
后序遍历序列:['d', 'e', 'b', 'f', 'g', 'c', 'a']
实现方法
class Node {
constructor(value) {
this.value = value
this.left = null
this.right = null
}
}
function fun(zhong, hou) {
// 严谨性判断
if (
zhong == null ||
hou == null ||
zhong.length == 0 ||
hou.length == 0 ||
zhong.length != hou.length
)
return null
// 根节点 -- 后序的最后一个元素
let root = new Node(hou[hou.length - 1]) // 创建根节点,值为后序遍历的最后一个元素
let index = zhong.indexOf(root.value) // 在中序遍历序列中找到根节点的索引
let zhongLeft = zhong.slice(0, index) // 中序遍历序列的左子树部分
let zhongRight = zhong.slice(index + 1) // 中序遍历序列的右子树部分
let houLeft = hou.slice(0, index) // 后序遍历序列的左子树部分
let houRight = hou.slice(index, hou.length - 1) // 后序遍历序列的右子树部分
root.left = fun(zhongLeft, houLeft) // 递归构建左子树
root.right = fun(zhongRight, houRight) // 递归构建右子树
return root // 返回构建好的根节点
}
const root = fun(zhong, hou)
console.log(root)