由前序遍歷和中序遍歷構建二叉樹
阿新 • • 發佈:2018-07-09
[] for 中序 break pan n) turn star 前序遍歷
public Node reConstructBinaryTree(int[] pre,int[] in){ if(pre==null || in ==null){ return null; } Node mm = reConstructBinaryTree(pre,in,0,pre.length-1,0,in.length-1); return mm; } public Node reConstructBinaryTree(int[] pre,int[] in,int preStart,intpreEnd,int inStart,int inEnd){ Node node = new Node(pre[preStart]); node.left = null; node.right = null; if(preStart == preEnd && inStart == inEnd){ return node; } int root = 0; for(root = instart;root<inEnd;root++){if(pre[preStart] == in[root]){ break; } } int leftLength = root-inStart; int rightLength = inEnd-root; if(leftLength>0){ node.left = reConstructBinaryTree(pre,in,preStart+1,preStart+leftLength,inStart,root-1); }if(rightLength>0){ node.right = reConstructBinaryTree(pre,in,preStart+leftLength,root+1,inEnd); } return node; }
由前序遍歷和中序遍歷構建二叉樹