根据前序和中序,使用JavaScript编写代码得到二叉树
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var qian = ["a", "b", "d", "e", "c", "f", "g"]; var zhong = ["d", "b", "e", "a", "f", "c", "g"]; function Node(value){ this.value = value; this.left = null; this.right = null; } //通过前序和中序还原二叉树 function resumeTree(qian, zhong){ if(qian == null || zhong == null || qian.length == 0 || zhong.length == 0 || qian.length != zhong.length) return null;//qian和zhong数组为null或者长度为0,或者两者长度不相等,直接返回 var root = new Node(qian[0]);//前序第一个节点是二叉树的根节点 var index = zhong.indexOf(qian[0]);//找到中序里根节点所在的索引 var zhongLeft = zhong.slice(0, index);//获取中序的左子树 var zhongRight = zhong.slice(index + 1, zhong.length);//获取中序的右子树 var qianLeft = qian.slice(1, index + 1);//获取前序的左子树 var qianRight = qian.slice(index + 1, qian.length);//获取前序的右子树 root.left = resumeTree(qianLeft, zhongLeft);//找到节点的左节点 root.right = resumeTree(qianRight, zhongRight);//找到节点的右节点 return root;//返回二叉树 } var tree = resumeTree(qian, zhong);//获取二叉树 console.log(tree.left);//打印左子树 console.log(tree.right);//打印右子树 </script> </body> </html>
根据中序和后续,使用JavaScript编写代码得到二叉树
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> var hou = ["d", "e", "b", "f", "g", "c", "a"]; var zhong = ["d", "b", "e", "a", "f", "c", "g"]; function Node(value){ this.value = value; this.left = null; this.right = null; } //通过后序和中序还原二叉树 function resumeTree(hou, zhong){ if(hou == null || zhong == null || hou.length == 0 || hou.length == 0 || hou.length != zhong.length) return null;//hou和zhong数组为null或者长度为0,或者两者长度不相等,直接返回 var root = new Node(hou[hou.length - 1]);//后序最后一个节点是二叉树的根节点 var index = zhong.indexOf(hou[hou.length - 1]);//找到中序里根节点所在的索引 var zhongLeft = zhong.slice(0, index);//获取中序的左子树 var zhongRight = zhong.slice(index + 1, zhong.length);//获取中序的右子树 var houLeft = hou.slice(0, index);//获取后序的左子树 var houRight = hou.slice(index, hou.length - 1);//获取后序的右子树 root.left = resumeTree(houLeft, zhongLeft);//找到节点的左节点 root.right = resumeTree(houRight, zhongRight);//找到节点的右节点 return root;//返回二叉树 } var tree = resumeTree(hou, zhong);//获取二叉树 console.log(tree.left);//打印左子树 console.log(tree.right);//打印右子树 </script> </body> </html>