tags: Sword finger offer
Enter the results of pre-order traversal and middle-order traversal of a binary tree, and please rebuild the binary tree. Assume that the input result of pre-order traversal and middle-order traversal does not contain repeated numbers. For example, input the pre-order traversal sequence {1,2,4,7,3,5,6,8} and the middle-order traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the binary tree and return.
/**
* Refactor the binary tree
*/
public class Test4 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
TreeNode root = resConstructBinaryTree(
pre,0,pre.length-1,
in,0,in.length-1);
return root;
}
public TreeNode resConstructBinaryTree(int [] pre,int startPre,int endPre,
int [] in,int startIn,int endIn){
if (startPre > endPre || startIn > endIn){
return null;
}
TreeNode node = new TreeNode(pre[startPre]);
for (int i = startIn; i <= endIn; i++){
if (in[i] == pre[startPre]){
node.left = resConstructBinaryTree(
pre,startPre+1,startPre+i-startIn,
in,startIn,i-1);
node.right = resConstructBinaryTree(
pre,startPre+i-startIn+1,endPre,
in,i+1,endIn);
break;
}
}
return node;
}
}
About the tree, the time to interview is to check the binary tree Width-first traversal and depth-first traversal Where depth-first traversal: Preorder traversal In-order traversal Post-order traversa...
Reconstruction of a binary tree Involving knowledge points: tree Title Description And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Sup...
The classic binary topic using recursive solution For a large part of the tree are recursive problem solving Thinking Before each take a first-order traversal, and after finding the corresponding loca...
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 fre...
Problem 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 nu...
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. Befo...
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. For ...
Rebuild the binary tree Two ways...
layout: post title: 04- reconstructed binary tree category: offer to prove safety tags: description: Title Description And enter the result in a preorder traversal of a binary tree in preorder travers...