劍指Offer-根據二叉樹的前序和後序遍歷重建二叉樹
阿新 • • 發佈:2019-01-28
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。
* 假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。* 例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}
* 和中序遍歷序列{4,7,2,1,5,3,8,6},
* 則重建二叉樹並返回
/*思路:在二叉樹的前序遍歷中,第一個數值總是根節點的值,而在中序遍歷中,根節點的值在序列的中間部分, * 所以,我們可以通過前序遍歷中的第一個根節點在中序遍歷中找到這個節點,該節點的左右兩邊分別是根節點 * 的左子樹和右子樹,在通過遞迴迴圈以上步驟求出左子樹和右子樹即可。 * */ class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class ReConstructBinaryTree { private int index=-1; public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre==null||in==null){ return null; } TreeNode root=build(pre,in,0,in.length-1); return root; } public TreeNode build(int [] pre,int [] in,int left,int right){ if(left>right){ return null; } ++index; TreeNode treeNode=new TreeNode(pre[index]); int i; for(i=left;i<=right;i++){ if(pre[index]==in[i]){ break; } } TreeNode leftNode=build(pre,in,left,i-1); TreeNode rightNode=build(pre,in,i+1,right); treeNode.left=leftNode; treeNode.right=rightNode; return treeNode; } public static void main(String[] args) { ReConstructBinaryTree re=new ReConstructBinaryTree(); /*int pre[]={1,2,4,7,3,5,6,8}; int in[]={4,7,2,1,5,3,8,6};*/ int pre[]={1,2,4,3,5,6}; int in[]={4,2,1,5,3,6}; TreeNode root=re.reConstructBinaryTree(pre,in); } }