
1️⃣ 二叉树的前序遍历
function Node(value) {this.value = value;this.left = null;this.right = null;}var a = new Node("a")var b = new Node("b")var c = new Node("c")var d = new Node("d")var e = new Node("e")var f = new Node("f")var g = new Node("g")var h = new Node("h")var i = new Node("i")var j = new Node("j")var k = new Node("k")a.left = b;a.right = c;b.left = d;b.right = e;c.left = f;c.right = g;d.left = h;d.right = i;g.left = j;g.right = k;function fun(root) {if (root == null || root.length == 0) return;console.log(root.value);fun(root.left);fun(root.right);}fun(a); // a b d h i e c f g j k
1️⃣ 二叉树的中序遍历
function Node(value) {this.value = value;this.left = null;this.right = null;}var a = new Node("a")var b = new Node("b")var c = new Node("c")var d = new Node("d")var e = new Node("e")var f = new Node("f")var g = new Node("g")var h = new Node("h")var i = new Node("i")var j = new Node("j")var k = new Node("k")a.left = b;a.right = c;b.left = d;b.right = e;c.left = f;c.right = g;d.left = h;d.right = i;g.left = j;g.right = k;function fun(root) {if (root == null || root.length == 0) return;fun(root.left);console.log(root.value);fun(root.right);}fun(a); // h d i b e a f c j g k
1️⃣ 二叉树的后序遍历
function Node(value) {this.value = value;this.left = null;this.right = null;}var a = new Node("a")var b = new Node("b")var c = new Node("c")var d = new Node("d")var e = new Node("e")var f = new Node("f")var g = new Node("g")var h = new Node("h")var i = new Node("i")var j = new Node("j")var k = new Node("k")a.left = b;a.right = c;b.left = d;b.right = e;c.left = f;c.right = g;d.left = h;d.right = i;g.left = j;g.right = k;function fun(root) {if (root == null || root.length == 0) return;fun(root.left);fun(root.right);console.log(root.value);}fun(a); // h i d e b f j k g c a
1️⃣ 根据前序中序还原二叉树
前序结果:a b d h i e c f g j k
中序结果:h d i b e a f c j g k
const qian = ['a', 'b', 'd', 'h', 'i', 'e', 'c', 'f', 'g', 'j', 'k'];const zhong = ['h', 'd', 'i', 'b', 'e', 'a', 'f', 'c', 'j', 'g', 'k'];const hou = ['h', 'i', 'd', 'e', 'b', 'f', 'j', 'k', 'g', 'c', 'a'];function Node(value) {this.value = value;this.left = null;this.right = null;}function fun(qian, zhong) {if (qian == null || zhong == null || qian.length == 0 || zhong.length == 0)return null;var root = new Node(qian[0]);var index = zhong.indexOf(root.value); // 找到根节点在中序遍历中的位置var qianLeft = qian.slice(1, 1 + index); // 前序遍历的左子树var qianRight = qian.slice(1 + index, qian.length); // 前序遍历的右子树var zhongLeft = zhong.slice(0, index); //中序遍历的左子树var zhongRight = zhong.slice(index + 1, zhong.length); // 中序遍历的右子树root.left = fun(qianLeft, zhongLeft); // 根据左子树的前序和中序还原左子树并赋值给 root.leftroot.right = fun(qianRight, zhongRight); // 根据右子树的前序和中序还原右子树并赋值给 root.rightreturn root;}var root = fun(qian, zhong);console.log(root);
1️⃣ 根据中序后序还原二叉树
中序结果:h d i b e a f c j g k
后序结果: h i d e b f j k g c a
