标签:dex 查找 order new ref 假设 range hashmap 建二叉树
1.要点
map
preorder =?[3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ 9 20
/ 15 7
0 <= 节点个数 <= 5000
public TreeNode buildTree(int[] preorder, int[] inorder) {
return preorder.length == 0 ? null : buildNode(preorder, inorder);
}
public TreeNode buildNode(int[] preorder, int[] inorder) {
int rootNodeIndex = -1;
int rootNodeValue = 0;
Map<Integer,Integer> inorderMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
inorderMap.put(inorder[i],i);
}
for (int i = 0; i < preorder.length; i++) {
if (null != inorderMap.get(preorder[i])) {
rootNodeIndex = inorderMap.get(preorder[i]);
rootNodeValue = preorder[i];
break;
}
}
TreeNode treeNode = new TreeNode(rootNodeValue);
treeNode.left = rootNodeIndex > 0 ?
buildNode(preorder, Arrays.copyOfRange(inorder, 0, rootNodeIndex)) :
null;
treeNode.right = rootNodeIndex < inorder.length - 1 ?
buildNode(preorder, Arrays.copyOfRange(inorder, rootNodeIndex + 1, inorder.length)) :
null;
return treeNode;
}
标签:dex 查找 order new ref 假设 range hashmap 建二叉树
原文地址:https://www.cnblogs.com/yuyy114/p/13195016.html