# topic:

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.

# Problem solving:

```链接：https://www.nowcoder.com/questionTerminal/8a19cbe657394eeaac2f6ea9b0f6fcf6?answerType=1&f=discussion

/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre.length == 0 || in.length == 0) {
return null;
}
The root the TreeNode ; = new new the TreeNode (pre [0 ]);
// find the roots in the preamble in order
for ( int I = 0; I <in.length; I ++ ) {
IF (in [I] == pre [0 ]) {
// left subtree, attention copyOfRange functions, left and right to open and close
root.left = reConstructBinaryTree (Arrays.copyOfRange (pre,. 1, I +. 1), Arrays.copyOfRange (in, 0 , I));
// right subtree, attention copyOfRange functions, left and right to open and close
root.right = reConstructBinaryTree (Arrays.copyOfRange (pre, I +. 1, pre.length), Arrays.copyOfRange (in, I +. 1 , in.length));
BREAK
}
}
return root;
}
}```

### Guess you like

Origin www.cnblogs.com/yanhowever/p/12020761.html
Recommended
Ranking
Daily