构建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
java
public class TreeNode {
TreeNode left = null;
TreeNode rigth = null;
int val = 0;
TreeNode(int val){
this.val = val;
}
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
int i = 0;
int len = pre.length;
if (pre.length ==0||in.length == 0 || pre.length != in.length){
return null;
}
TreeNode root = new TreeNode(pre[0]);
while (in[i] != root.val){
i++;
}
int[] preLeft = new int[i];
int[] preRight = new int[len - 1 -i];
int[] inLeft = new int[i];
int[] inRigth = new int[len -1-i];
for (int j = 0;j<len;j++){
if (j<i){
preLeft[j] = pre[j+1];
inLeft[j] = in[j];
}else if(j > i){
preRight[j-i-1] = pre[j];
inRigth[j-i-1]=in[j];
}
}
root.left = reConstructBinaryTree(preLeft,inLeft);
root.rigth=reConstructBinaryTree(preRight,inRigth);
return root;
}
}
pyhton:
class TreeNode:
def __init__(self,val):
self.val = val
self.left = None;
self.right = None;
def reConstructBinaryTree(self, pre, tin):
if not pre or not tin:
return None
root = TreeNode(pre[0])
root.val = pre[0]
i = tin.index(root.val)
root.left = self.reConstructBinaryTree(pre[1:i+1],tin[0:i])
root.right = self.reConstructBinaryTree(pre[i+1:],tin[i+1:])
return root