重建二叉树
题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
起初看到这题我真的无从下手,准确的说是无法写代码,因为自己只做过这类的笔试题,比如之前数据结构考试和软考,
但是我只停留在会做题和知道大概思想的层面,代码实现真的不会,之后看了讨论区牛客大佬的答案,不得不佩服666
这里采用的是递归的思想,首先,拿题目中的例子看,前序遍历第一个即1肯定是整个树的根节点,由此.可以得出,在中序遍历
的数组中,1之前是整个树的左子树.而1之后,为整个树的右子树,然后接着找左子树和右子树的根节点,然后按照同样的方式再分
左右树,startPre+1到startPre+i就是1的左子树的节点的个数,这一段相当于通过索引把元素传到下一个递归中,而i-startIn+startPre-1
是计算右子树元素在数组中开始的位置
/** * @param in 中序 * @param pre 先序遍历 * */ public static TreeNode reConstructBinaryTree(int [] pre,int [] in) { return reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1); } private static TreeNode reConstructBinaryTree(int[] pre,int startPre,int endPre,int[] in,int startIn,int endIn){ if(startPre>endPre||startIn>endIn) return null; TreeNode tree = new TreeNode(pre[startPre]); for (int i = startIn;i<endIn;i++){ if (in[i]==pre[startPre]){ //System.out.println("left= pre "+pre[startPre+1]+"-"+pre[startPre+i]+" -- in "+in[startIn]+"-"+in[i-1]); //System.out.println("right= pre "+pre[i-startIn+startPre+1]+"-"+pre[endPre]+" -- in "+in[i+1]+"-"+in[endIn]); tree.left = reConstructBinaryTree(pre,startPre+1,startPre+i,in,startIn,i-1); tree.right = reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn); break; } } return tree; } public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
看了之后深感自己太菜,溜了溜了