输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
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, tin): 10 n = len(pre) 11 if n == 0: 12 return None 13 if n == 1: 14 return TreeNode(pre[0]) 15 root = TreeNode(pre[0]) 16 for i in range(len(tin)): 17 if tin[i] == pre[0]: 18 break 19 root.left = self.reConstructBinaryTree(pre[1:i+1],tin[:i]) 20 root.right = self.reConstructBinaryTree(pre[i+1:],tin[i+1:]) 21 return root 22 # write code here
补充Java的实现,leetcode地址:
1 class Solution { 2 public TreeNode buildTree(int[] preorder, int[] inorder) { 3 int n = preorder.length; 4 if (n == 0) { 5 return null; 6 } 7 if (n == 1) { 8 return new TreeNode(preorder[0]); 9 } 10 TreeNode root = new TreeNode(preorder[0]); 11 int len = inorder.length; 12 int i = 0; 13 while (i < len) { 14 if (inorder[i] == preorder[0]) { 15 break; 16 } 17 i++; 18 } 19 int[] newpre1 = Arrays.copyOfRange(preorder, 1, i + 1); 20 int[] newin1 = Arrays.copyOfRange(inorder, 0, i); 21 root.left = this.buildTree(newpre1, newin1); 22 23 int[] newpre2 = Arrays.copyOfRange(preorder, i + 1, preorder.length); 24 int[] newin2 = Arrays.copyOfRange(inorder, i + 1, inorder.length); 25 root.right = this.buildTree(newpre2, newin2); 26 27 return root; 28 } 29 }