【剑指offer】04 重建二叉树

题目地址:重建二叉树

 

题目描述                                   

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M

 

题目示例                                   

输入:
[1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
返回值:
{1,2,5,3,4,6,7}

 

解法分析                                   

通过前序和中序遍历重建二叉树,可以先找出root节点(也就是前序遍历的pre[0]),然后在中序遍历vin中找出root的位置,此时vin中root左侧和右侧的节点可以视为新的二叉树——左侧二叉树和右侧二叉树,继续对左侧二叉树和右侧二叉树用此方法直到没有新的(子)二叉树,即可得到重建的二叉树。

很明显,应该使用递归。

 

代码                                         

 1 /* function TreeNode(x) {
 2     this.val = x;
 3     this.left = null;
 4     this.right = null;
 5 } */
 6 function reConstructBinaryTree(pre, vin)
 7 {
 8     // write code here
 9     if(pre.length === 0 || vin.length === 0){
10         return null;
11     }
12     var root = vin.indexOf(pre[0]);
13     var left = vin.slice(0,root);
14     var right = vin.slice(root+1);
15     return{
16         val : pre[0],
17         left : reConstructBinaryTree(pre.slice(1,root+1),left),
18         right : reConstructBinaryTree(pre.slice(root+1),right)
19     };
20 }

 

执行结果                                   

 

posted @ 2020-12-23 14:24  月南君  阅读(95)  评论(0编辑  收藏  举报