二叉樹 根據前序遍歷 中序遍歷 寫出後序遍歷
阿新 • • 發佈:2019-01-10
思路
前序遍歷:中——左——右
中序遍歷:左——中——右
先確定前序遍歷的第一個節點為根節點,然後在中序遍歷中找到該根節點,以根節點為基點,前一部分為左子樹,後一部分為右子樹。然後按照遞迴分部分操作。
虛擬碼
主方法{
根節點 = 建立樹(0,節點個數-1,0,結點個數-1,前序節點陣列,中序節點陣列);
後續遍歷列印節點
}
建立樹(前序左,前序右,中序左,中序右,前序節點陣列,中序節點陣列){
if(前序左>前序右)返回空
新建根節點root = 前序節點陣列[前序左];
中序陣列索引 k = 0;
遍歷找到在 中序節點陣列中的根節點 的索引 並賦值為給 k ;
左子樹結點個數 num = k - 中序左;
root.左子樹 = 建立樹(前序左+1,前序左+num,中序左,k - 1,前序節點陣列,中序節點陣列);
root.右子樹 = 建立樹(前序左+1+num,前序右,k + 1,中序右 ,前序節點陣列,中序節點陣列);
返回根root;
}
列印節點(根節點root,結點個數){
if( root 為空 ) return;
列印節點(根節點root.左子樹,結點個數);
列印節點(根節點root.右子樹,結點個數);
輸出root的值
}
程式碼
public static void main(String[] args) { int [] pre = new int[] {4,2,1,3,5,7,6}; int [] in = new int [] {1,2,3,4,5,6,7}; int nodeNum = 7; TreeNode root = creat(0,nodeNum-1,0,nodeNum-1,pre,in);//建立樹 printPost(root,nodeNum);//列印節點 } static int num = 0; private static void printPost(TreeNode root,int nodeNum) { //後續遍歷 列印節點 if(root==null)return; printPost(root.left,nodeNum); printPost(root.right,nodeNum); System.out.print(root.val); num++; if(num<nodeNum)System.out.print(" "); } private static TreeNode creat(int prel, int prer, int inl, int inr,int[]pre,int []in) { if(prel>prer) return null; TreeNode root = new TreeNode(pre[prel]);//建立根節點 int k = 0; //根節點在中序陣列中的索引 for (k = inl; k < in.length; k++) { //找到找到索引 if(pre[prel]==in[k]) { break; } } int numleft = k - inl; //左子樹節點個數 //引數依次為 (在前序陣列中 左子樹起始位置,在前序陣列中 左子樹終止位置, // 在中序陣列中 左子樹起始位置,在前序陣列中 左子樹終止位置, // 前序陣列,中序陣列) root.left = creat(prel+1, prel+numleft, inl, k-1, pre, in); //引數依次為 (在前序陣列中 右子樹起始位置,在前序陣列中 右子樹終止位置, // 在中序陣列中 右子樹起始位置,在前序陣列中 右子樹終止位置, // 前序陣列,中序陣列) root.right = creat(prel+numleft+1, prer, k+1, inr, pre, in); return root; }