图片可能描述的不是太清晰,看下代码吧
var qian = ['a', 'c', 'f', 'g', 'b', 'd', 'e'];
var zhong = ['f', 'c', 'g', 'a', 'd', 'b', 'e'];
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function f1(qian, zhong) {
if (qian == null || zhong == null || qian.length == 0 || zhong.length == 0 || qian.length != zhong.length) return null;
var root = new Node(qian[0]); //根据前序遍历的规则找到这棵树的根节点
var index = zhong.indexOf(root.value); // 找到根节点在中序遍历中的位置
// console.log(index) // 3
var qianLeft = qian.slice(1, 1 + index); // 截取前序遍历的左子树
var qianRight = qian.slice(1 + index, qian.length); // 截取前序遍历的右子树
// console.log(qianLeft,qianRight) // [ 'c', 'f', 'g' ] [ 'b', 'd', 'e' ]
var zhongLeft = zhong.slice(0, index); // 截取中序遍历的左子树
var zhongRight = zhong.slice(index + 1, zhong.length); // 截取中序遍历的右子树
// console.log(zhongLeft,zhongRight) // [ 'f', 'c', 'g' ] [ 'd', 'b', 'e' ]
root.left = f1(qianLeft, zhongLeft); // 根据左子树的前序和中序还原左子树并赋值给root.left
root.right = f1(qianRight, zhongRight) // 根据右子树的谦虚和中序还原右子树并赋值给root.right
// console.log(root.value) // 打印出后序遍历
return root;
}
var root = f1(qian, zhong); // 还原二叉树
console.log(root)