image.png

前序中序还原二叉树

  1. const qian = ["a", "c", "f", "g", "b", "d", "e"]
  2. const zhong = ["f", "c", "g", "a", "d", "b", "e"]
  3. class Node {
  4. constructor(value) {
  5. this.value = value;
  6. this.left = null;
  7. this.right = null;
  8. }
  9. }
  10. function f1(qian, zhong) {
  11. if (qian == null || zhong == null || qian.length == 0 || zhong.length == 0 || qian.length !== zhong.length) return null;
  12. let root = new Node(qian[0]); //前序排序第一个是根节点
  13. let index = zhong.indexOf(root.value) // 找到根节点在中序遍历中的位置
  14. let qianLeft = qian.slice(1, 1 + index) //前序遍历中左子树
  15. let qianRight = qian.slice(1 + index, qian.length) // 前序遍历中右子树
  16. let zhongLeft = zhong.slice(0, index) // 中序遍历中的左子树
  17. let zhongRight = zhong.slice(index + 1, zhong.length) // 中序遍历中的右子树
  18. root.left = f1(qianLeft, zhongLeft)
  19. root.right = f1(qianRight, zhongRight)
  20. return root
  21. }
  22. var root = f1(qian, zhong)
  23. console.log(root.left)
  24. console.log(root.right)

运行结果
image.png

中序后序还原二叉树

  1. const zhong = ["f", "c", "g", "a", "d", "b", "e"]
  2. const hou = ["f", "g", "c", "d", "e", "b", "a"]
  3. class Node {
  4. constructor(value) {
  5. this.value = value;
  6. this.left = null;
  7. this.right = null;
  8. }
  9. }
  10. function f1(zhong, hou) {
  11. if (hou == null || zhong == null || hou.length == 0 || zhong.length == 0 || hou.length !== zhong.length) return null;
  12. let root = new Node(hou[hou.length - 1]) //后序遍历中的根节点在最后
  13. let index = zhong.indexOf(root.value) // 获取根节点在中序遍历中的位置
  14. let zhongLeft = zhong.slice(0, index) // 中序遍历左子树
  15. let zhongRight = zhong.slice(index + 1, zhong.length) // 中序遍历右子树
  16. let houLeft = hou.slice(0, index) // 后序遍历左子树
  17. let houRight = hou.slice(index, hou.length - 1) // 后序遍历右子树
  18. root.left = f1(zhongLeft, houLeft)
  19. root.right = f1(zhongRight, houRight)
  20. return root;
  21. }
  22. var root = f1(zhong,hou)
  23. console.log(root.left)
  24. console.log(root.right)