對於二叉樹,由前序遍歷和中序遍歷或中序遍歷和後序遍歷均可以還原二叉樹,可是由前序遍歷和後序遍歷沒法還原二叉樹,由於沒法肯定左子樹和右子樹的位置。html
根據前序遍歷和中序遍歷還原二叉樹:java
由前序遍歷的第一個值能夠肯定根節點,再由中序遍歷找到根節點的位置,其左邊的爲左子樹,右邊的爲右子樹。數組
再重構前序遍歷結果和中序遍歷結果,再遞歸上述過程便可徹底還原二叉樹。測試
在寫代碼前先簡單介紹一下java中的System.arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)spa
其中:src表示源數組,srcPos表示源數組要複製的起始位置,desc表示目標數組,desPos表示目的數組複製的起始位置,length表示要複製的長度。code
public class Solution { public static TreeNode reConstructBinaryTree(int [] prev,int [] in) { //無論什麼遍歷方式,結果長度確定是同樣的,都是總結點數 if(prev.length!= in.length || prev.length<1){ return null; } //只有一個節點,那就是根節點 if(prev.length == 1){ return new TreeNode(prev[0]); } //在中序遍歷結果中找根節點 int index = -1; for(int i=0;i<in.length;i++){ if(in[i]==prev[0]){ index=i; break; } } //沒找到,說明數據有問題 if(index==-1){ return null; } //找到根節點了 TreeNode root = new TreeNode(prev[0]); //獲得左子樹的前序遍歷結果 int[] lChildPrev = new int[index]; System.arraycopy(prev,1,lChildPrev,0,index); //獲得左子樹的中序遍歷結果 int[] lChildin = new int[index]; System.arraycopy(in,0,lChildin,0,index); //經過遞歸,獲得左子樹結構 root.left=reConstructBinaryTree(lChildPrev,lChildin); //獲得右子樹的前序遍歷結果 int[] rChildPrev = new int[in.length-1-index]; System.arraycopy(prev,index+1,rChildPrev,0,in.length-1-index); //獲得右子樹的中序遍歷結果 int[] rChildin = new int[in.length-1-index]; System.arraycopy(in,index+1,rChildin,0,in.length-1-index); //經過遞歸,獲得右子樹結構 root.right=reConstructBinaryTree(rChildPrev,rChildin); //獲得完整的二叉樹結構 return root; } //測試 public static void main(String[] args){ int[] prev = {1,2,4,7,3,5,6,8}; int[] in = {4,7,2,1,5,3,8,6}; TreeNode root = reConstructBinaryTree(prev,in); prevPrintTreeNode(root); System.out.println(); inPrintTreeNode(root); } //測試結果 //1 2 4 7 3 5 6 8 //4 7 2 1 5 3 8 6 }
原文出處:https://www.cnblogs.com/wenbinshen/p/11213973.htmlhtm