java 重建二叉树_【剑指offer】 Java实现重建二叉树
/**
* @Author: DaleyZou
* @Description: 重建二叉樹
* 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。
* 假設輸入的前序遍歷和中序遍歷的結果中都不含重復的數字。
* 例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹并返回。
* @Date: Created in 7:58 2019/1/29
* @Modified By:
*/
public class ConstructBinaryTree_4 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/**
* 緩存中序遍歷數組每個值對應的索引
*/
private Map indexForInOrders = new HashMap<>();
public TreeNode reConstructBinaryTree(int [] pre, int [] in) {
for (int i = 0; i < in.length; i++){
indexForInOrders.put(in[i], i);
}
return reConstructBinaryTree(pre, 0, pre.length - 1, 0);
}
public TreeNode reConstructBinaryTree(int [] pre, int preL, int preR, int inL){
if (preL > preR){
return null;
}
TreeNode root = new TreeNode(pre[preL]);
int inIndex = indexForInOrders.get(root.val);
int leftTreeSize = inIndex - inL;
root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, inL);
root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, inL + leftTreeSize + 1);
return root;
}
public static void main(String[] args){
int[] pre = new int[]{1,2,4,7,3,5,6,8};
int[] in = new int []{4,7,2,1,5,3,8,6};
ConstructBinaryTree_4 constructBinaryTree = new ConstructBinaryTree_4();
TreeNode treeNode = constructBinaryTree.reConstructBinaryTree(pre, in);
System.out.println(treeNode.val);
}
}
總結
以上是生活随笔為你收集整理的java 重建二叉树_【剑指offer】 Java实现重建二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python类中方法相互调用_pytho
- 下一篇: java 异常管理员_java web在