题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:
前序第一个就是根结点,在中序中找到这个值,其左边是左子树部分,右边是右子树部分,然后利用递归,每个小子树都是这么做。
Java
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public class S4_ReConstructBinaryTree {
public TreeNode reConstructBinaryTree(int[] pre, int[] in){
TreeNode root = reConstruct(pre, 0, pre.length-1, in, 0, in.length-1);
return root;
}
private TreeNode reConstruct(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd){
if (preStart > preEnd || inStart > inEnd)
return null;
TreeNode root = new TreeNode(pre[preStart]); //前序第一个即是根节点
for (int i=inStart;i<=inEnd;i++){
if (in[i] == pre[preStart]){
root.left = reConstruct(pre, preStart+1, preStart+i-inStart, in, inStart,i-1);
root.right = reConstruct(pre, preStart+i-inStart+1, preEnd, in, i+1, inEnd);
break;
}
}
return root;
}
public static void main(String[] args){
S4_ReConstructBinaryTree s4 = new S4_ReConstructBinaryTree();
int[] pre = {3, 9, 20, 15, 7};
int[] in = {9, 3, 15, 20, 7};
TreeNode root = s4.reConstructBinaryTree(pre, in);
PrintTreeLayer p = new PrintTreeLayer();
p.printTreeLayer(root);
}
}
其中PrintTreeLayer是专门把数组转换成二叉树,并按行打印出来,其中空结点用null表示。
结果:
"D:\Program Files\Java\jdk1.8.0_31\bin\java.exe"
3 9 20 null null 15 7
Python
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def reConstructBinaryTree(self, pre, tin):
if len(pre) == 0:
return None
if len(pre) == 1:
return TreeNode(pre[0])
else:
root = TreeNode(pre[0])
root.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1],tin[:tin.index(pre[0])])
root.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:],tin[tin.index(pre[0])+1:] )
return root
if __name__ =='__main__':
pre = [1, 2, 4, 7, 3, 5, 6, 8]
tin = [4, 7, 2, 1, 5, 3, 8, 6]
test = Solution()
result = test.reConstructBinaryTree(pre, tin)
print(result.val)