不知何故,我设法编写了一个算法,用于从它的中序和前序遍历数据构造二叉树。
我不确定如何计算该算法的时间和空间复杂度。
我的猜测是
first pass --> n(findInNode) + n/2 (constructTree) + n/2 (constructTree)
second pass --> n/2(findInNode) + n/4 (constructTree) + n/4 (constructTree)
etc..
所以它应该是大约(3logn)
如果我错了,请纠正我。
public class ConstructTree {
public static void main(String[] args) {
int[] preOrder = new int[] { 1, 2, 3, 4, 5 };
int[] inOrder = new int[] { 2, 1, 4, 3, 5 };
int start = 0;
int end = inOrder.length -1;
Node root =constructTree(preOrder, inOrder, start, end);
System.out.println("In order Tree"); root.inOrder(root);
System.out.println("");
System.out.println("Pre order Tree"); root.preOrder(root);
System.out.println("");
}
public static int preInd = 0;
public static Node constructTree(int[] pre, int[] in, int start, int end) {
if (start > end) {
return null;
}
int nodeVal = pre[preInd++];
Node node = new Node(nodeVal);
if (start != end) {
int ind = findInNode(nodeVal, in, start, end);
node.left = constructTree(pre, in, start, ind-1);
node.right = constructTree(pre, in, ind+1, end);
}
return node;
}
public static int findInNode(int nodeVal, int[] in, int start, int end) {
int i = 0;
for (i = start; i <= end; i++) {
if(in[i] == nodeVal)
{
return i;
}
}
return -1;
}
}