还原二叉树
还原二叉树,已知前序遍历,和中序遍历,后序遍历,还原二叉树
//定义二叉树
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
已知前序遍历,和中序遍历,后序遍历,还原二叉树
// 前序遍历的值
var VLRValue = ["a", "b", "d", "e", "c", "f"]
// 中序遍历的值
var LDRValue = ["d", "b", "e", "a", "f", "c"]
// 后序遍历的值
var LRDValue = ["d", "e", "b", "f", "c", "a"]
//已知前序遍历,和中序遍历,还原二叉树
function BinaryTree(VLR, LDR) {
if (VLR === null || LDR === null || VLR.length == 0 || LDR.length == 0 || VLR.length !== LDR.length) return;
var root = new Node(VLR[0])
var index = LDR.indexOf(root.value)
var VLRLeft = VLR.slice(1, 1 + index)
var VLRRight = VLR.slice(1+index, VLR.length)
var LDRLeft = LDR.slice(0, index)
var LDRRight = LDR.slice(index+1,LDR.length)
root.left = BinaryTree(VLRLeft, LDRLeft)
root.right = BinaryTree(VLRRight, LDRRight)
return root
}
var root = BinaryTree(VLRValue, LDRValue)
console.log('root: ', root);
// 已知中序遍历,后序遍历,还原二叉树
function BinaryTree(LDR, LRD) {
if (LDR == null || LRD == null || LDR.length == 0 || LRD == 0 || LDR.length !== LRD.length) return;
var root = new Node(LRD[LRD.length - 1])
console.log('root: ', root);
var index = LDR.indexOf(root);
var LRDLeft = LRD.slice(0, index);
var LRDRight = LRD.slice(index, LRD.length - 1)
var LDRLeft = LDR.slice(0, index);
var LDRRignt = LDR.slice(index + 1, LDR.length)
root.left = BinaryTree(LDRLeft, LRDLeft)
root.right = BinaryTree(LDRRignt, LRDRight)
return root
}
var root = BinaryTree(LDRValue, LRDValue)
console.log('root: ', root);