面试题6:重建二叉树
2017-11-22 20:37
225 查看
题目:根据某二叉树的前序遍历和中序遍历结果,重建该二叉树
思路:前序遍历的第一个数字就是根节点,在中序遍历中找到根节点,根节点左边是左子树节点,根节点右边是右子树节点;这样递归构建
思路:前序遍历的第一个数字就是根节点,在中序遍历中找到根节点,根节点左边是左子树节点,根节点右边是右子树节点;这样递归构建
public BinaryTreeNode constructCore(int[] pre,int[] in) { if(pre==null||in==null||pre.length!=in.length) { return null; } return constructCore(pre,in,0,pre.length-1,0,in.length-1); } private BinaryTreeNode constructCore(int[] pre,int[] in,int startPre,int endPre,int startIn,int endIn) { //根节点是前序遍历第一个元素 BinaryTreeNode root=new BinaryTreeNode(pre[startPre]); //在中序遍历中找到根节点 int rootIn=startIn; while(in[rootIn]!=pre[startPre]&&rootIn<endIn) { rootIn++; } int length=rootIn-startIn; //构建左子树 if(length>0) { root.left=constructCore(pre,in,startPre+1,startPre+length,startIn,rootIn-1); } //构建右子树 if(length<endPre-startPre) { root.right=constructCore(pre,in,startPre+length+1,endPre,rootIn+1,endIn); } //返回根节点 return root; }
相关文章推荐
- 剑指offer 面试题6—重建二叉树
- 剑指offer面试题6 重建二叉树(java)
- [剑指offer][面试题06]重建二叉树
- 面试题6:重建二叉树(前序遍历和中序遍历)
- 面试题----重建二叉树
- 剑指offer 面试题6 重建二叉树 java版答案
- 剑指offer 面试题6 重建二叉树2
- (剑指Offer)面试题6:重建二叉树
- 面试题6:重建二叉树(根据前序和中序)
- 剑指offer--面试题7:重建二叉树
- 剑指offer面试题6--重建二叉树
- 《剑指offer》(面试题6):重建二叉树
- 面试题5:重建二叉树
- 面试题7:重建二叉树(offer)
- 剑指offer面试题06 重建二叉树
- 面试题6:重建二叉树
- 面试题 6: 重建二叉树
- 剑指Offer面试题6(Java版):重建二叉树
- 剑指Offer面试题6重建二叉树(根据前序中序输出后序)
- 剑指offer-chapter2-面试题6-重建二叉树(java)