我正在通过一种方法从给定的预订和顺序数组构建二叉树,但我无法理解下面的步骤
preorder_start + offset - inorder_start
preorder_start + offset - inorder_start + 1
在方法setLeft()
和setRight()
中作为参数传递。如果有人能用一个例子来解释我,那将是一个很好的帮助。
public BinaryTreeNode buildTreeFromInorderAndPreOrder(int[] preorder, int preorder_start, int preorder_end,
int[] inorder, int inorder_start, int inorder_end) {
if (preorder_start > preorder_end || inorder_start > inorder_end)
return null;
int data = preorder[preorder_start]; //We took the starting root data
BinaryTreeNode node = new BinaryTreeNode(data); //created a node containing data
int offset = inorder_start; //offset to point the index of data in inorder array
while (offset < inorder_end) { //while data is not matched in inorder array
if (inorder[offset] == data)
break; //we get the offset
offset++;
}
node.setLeft(buildTreeFromInorderAndPreOrder(preorder, preorder_start + 1,
preorder_start + offset - inorder_start, inorder, inorder_start, offset - 1));
node.setRight(buildTreeFromInorderAndPreOrder(preorder, preorder_start + offset - inorder_start + 1,
preorder_end, inorder, offset + 1, inorder_end));
return node; //finally return the node
}