4 重建二叉树
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:
前序遍历中,第一个点是根结点,根据这个根节点,去中序遍历中找,中序遍历根结点左右分别是左右子树。
根据这个思路递归的构建子树。
1 public class Solution { 2 public TreeNode reConstructBinaryTree(int [] pre,int [] in) { 3 return Construct(pre,0,pre.length-1,in,0,in.length-1); 4 } 5 private TreeNode Construct(int [] pre,int pre_start,int pre_end,int [] in,int in_start,int in_end) { 6 if(pre_start>pre_end||in_start>in_end) return null; 7 TreeNode root = new TreeNode(0); 8 for(int i = in_start;i<=in_end;i++){ 9 if(in[i]==pre[pre_start]){ 10 root.val = in[i]; 11 root.left = Construct(pre,pre_start+1,pre_start+i-in_start,in,in_start,i-1); 12 root.right= Construct(pre,pre_start+i-in_start+1,pre_end,in,i+1,in_end); 13 } 14 } 15 return root; 16 } 17 }
20180303
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 # 返回构造的TreeNode根节点 9 def reConstructBinaryTree(self, pre, inorder): 10 # write code here 11 def help(pre,inorder,p_first,p_last,in_first,in_last): 12 if(p_first>p_last or in_first>in_last): 13 return None 14 root = TreeNode(0) 15 for i in range(in_first,in_last+1): 16 if inorder[i] ==pre[p_first]: 17 root.val = inorder[i] 18 root.left = help(pre,inorder,p_first+1,p_first+(i-in_first),in_first,i-1); 19 root.right = help(pre,inorder,p_first+(i-in_first)+1,p_last,i+1,in_last) 20 return root 21 return help(pre,inorder,0,len(pre)-1,0,len(pre)-1) 22