算法-重建二叉树

来源:互联网 发布:百姓网发帖软件 编辑:程序博客网 时间:2024/06/06 13:56

问题描述:

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

我自己的答案:

package com.zjq.arithmetic;import java.util.ArrayList;import java.util.List;/** * 题目描述 * 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。 * 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。 * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}, * 则重建二叉树并返回。 * @author zjq * @Date 2017/08/08 * */public class BinaryTree {public static void main(String[] args) {int[] a = {1,2,4,7,3,5,6,8};int[] b = {4,7,2,1,5,3,8,6};BinaryTree binaryTree=new BinaryTree();binaryTree.reConstructBinaryTree(a, b);}public TreeNode reConstructBinaryTree(int[] pre, int[] in) {TreeNode treeNode;if(pre.length>=1) {      int midNode=pre[0];          List<Integer> inL=new ArrayList<Integer>();          List<Integer> inR=new ArrayList<Integer>();          List<Integer> preL=new ArrayList<Integer>();          List<Integer> preR=new ArrayList<Integer>();      int flag=0;  treeNode=new TreeNode(midNode);  for(int i=0;i<=in.length-1;i++) {  if(in[i]==midNode) {  flag=1;  }else {    if(flag==0) {    inL.add(in[i]);     }else {    inR.add(in[i]);    }  }  }  for(int i=1;i<=inL.size();i++) {  preL.add(pre[i]);  }    for(int i=inL.size()+1;i<pre.length;i++) {  preR.add(pre[i]);  }  if(preL.size()>0) {  int[] newPre=new int[preL.size()];  int[] newIn=new int[inL.size()];  for(int i=0;i<preL.size();i++) {  newPre[i]=preL.get(i);  }  for(int i=0;i<inL.size();i++) {  newIn[i]=inL.get(i);  }   treeNode.left=reConstructBinaryTree(newPre,newIn);  }  if(preR.size()>0) {  int[] newPre=new int[preR.size()];  int[] newIn=new int[inR.size()];  for(int i=0;i<preR.size();i++) {  newPre[i]=preR.get(i);  }  for(int i=0;i<inR.size();i++) {  newIn[i]=inR.get(i);  }   treeNode.right=reConstructBinaryTree(newPre,newIn);  }  return treeNode;}return null;}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}}

更好的解答方法:

链接:https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6来源:牛客网public class Solution {    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {        TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);        return root;    }    //前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}    private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) {                 if(startPre>endPre||startIn>endIn)            return null;        TreeNode root=new TreeNode(pre[startPre]);                 for(int i=startIn;i<=endIn;i++)            if(in[i]==pre[startPre]){                root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);                root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn);            }                         return root;    }}




原创粉丝点击