题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路一:找到中序中根节点所在位置,分为左子树,右子树递归调用重建
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(pre)==0 or len(tin)==0:
return None
root=TreeNode(pre[0])//创建根节点
pos=tin.index(pre[0])
root.left=self.reConstructBinaryTree(pre[1:pos+1],tin[:pos])//左子树
root.right=self.reConstructBinaryTree(pre[pos+1:],tin[pos+1:])//右子树
return root
**
* 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;
TreeNode root=new TreeNode(pre[0]);//构造新的对象
for(int i=0;i<=in.length-1;i++)
{
if (pre[0]==in[i]){//遍历,找到对应的根节点在中序中的索引
root.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));//复制一个新的数组操作递归
root.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));
}
}
return root;
}
}
思路二:
*写成递归函数的形式
*找到根在in中的位置i
*pre分为两个数组 [preStart + 1 , preStart + (i - inStart)] 和 [preEnd - (inEnd - i) + 1 , preEnd]
*in分为两个数组 [inStart , i - 1] 和 [i + 1 , inEnd]
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre, int [] in) {
TreeNode root = reConstructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
private TreeNode reConstructBinaryTree(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 (pre[preStart] == in[i])
{
root.left = reConstructBinaryTree(pre, preStart + 1, preStart + i - inStart, in, inStart, i - 1);
root.right = reConstructBinaryTree(pre, preEnd - (inEnd - i) + 1, preEnd, in, i + 1, inEnd);
}
}
return root;
}
}