一、根据前序中序还原二叉树
let qian = ["A", "B", "D", "E", "C", "F", "G"];
let zhong = ["D", "B", "E", "A", "F", "C", "G"];
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;
let root = new Node(qian[0]);
console.log(root.value); // ABDECFG
let index = zhong.indexOf(root.value);
let qianLeft = qian.slice(1, index + 1);
let qianRight = qian.slice(index + 1, qian.length);
let zhongLeft = zhong.slice(0, index);
let zhongRight = zhong.slice(index + 1, zhong.length);
root.left = f1(qianLeft, zhongLeft);
root.right = f1(qianRight, zhongRight);
return root;
}
const node = f1(qian, zhong);
console.log(node);
// Node {
// value: 'A',
// left: Node {
// value: 'B',
// left: Node { value: 'D', left: null, right: null },
// right: Node { value: 'E', left: null, right: null }
// },
// right: Node {
// value: 'C',
// left: Node { value: 'F', left: null, right: null },
// right: Node { value: 'G', left: null, right: null }
// }
// }
root.left = f1(qianLeft, zhongLeft);
root.right = f1(qianRight, zhongRight);
左边的树从左到右遍历完后,再遍历右边的树
右边的树在遍历过程中,也遵循从左到右遍历
都遍历完了最后从栈中拿出节点对应赋值还原出树
二、根据中序后序还原二叉树
let zhong = ["D", "B", "E", "A", "F", "C", "G"];
let hou = ["D", "E", "B", "F", "G", "C", "A"];
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function f1(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, zhong.length);
let houLeft = hou.slice(0, index);
let houRight = hou.slice(index, hou.length - 1);
root.left = f1(zhongLeft, houLeft);
root.right = f1(zhongRight, houRight);
return root;
}
const node = f1(zhong, hou);