## Offer reconstruction of a binary tree to prove safety

### Title Description

And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.

### Thinking

We know that the first node in a preorder traversal is the root of the tree, so let's create the root according to the preamble of the first digit traversal sequence, then find the location of the root node in preorder sequence, left sub-tree root is left, right is the right sub-tree, so that we can determine the number of left and right sub-tree node. After dividing the values ​​of the left, right subtree node and sequence preorder traversal order of the front, can be constructed recursively to each of its left and right subtrees.

### Reference Code

``````public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {

// 终止条件
if (pre == null || pre.length == 0) {
return null;
}

// 创建根节点
TreeNode root = new TreeNode(pre[0]);

// 获取到根节点在中序数组的索引
int index = findIndex(pre, in);

// 前序数组左子树的索引为[1, index + 1), 中序数组左子树的索引为[0, index)
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, index + 1), Arrays.copyOfRange(in, 0, index));

// 前序数组右子树的索引为[index + 1, pre.length), 中序数组右子树的索引为[index + 1, in.length)
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, index + 1, pre.length), Arrays.copyOfRange(in, index + 1, pre.length));

return root;
}

private int findIndex(int [] pre, int [] in) {
for (int i = 0; i < in.length; i++) {
if (in[i] == pre[0]) {
return i;
}
}
return -1;
}
}
``````
Released seven original articles · won praise 0 · Views 1353

### Guess you like

Origin blog.csdn.net/Incanus_/article/details/105241351
Recommended
Ranking
Daily