Construct Binary Tree from Preorder and Inorder Traversal

来源:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal

Java

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public TreeNode buildTree(int[] preorder, int[] inorder) {
12         if(preorder.length == 0) {
13             return null;
14         }
15         TreeNode root = new TreeNode(preorder[0]);
16         int rootIndex = 0;
17         while(rootIndex < inorder.length) {
18             if(inorder[rootIndex] == preorder[0]) {
19                 break;
20             }
21             rootIndex++;
22         }
23         int[] preLeftSubTree = Arrays.copyOfRange(preorder, 1, rootIndex+1);
24         int[] preRightSubTree = Arrays.copyOfRange(preorder, rootIndex+1, preorder.length);
25         int[] inLeftSubTree = Arrays.copyOfRange(inorder, 0, rootIndex);
26         int[] inRightSubTree = Arrays.copyOfRange(inorder, rootIndex+1, inorder.length);
27         root.left = buildTree(preLeftSubTree, inLeftSubTree);
28         root.right = buildTree(preRightSubTree, inRightSubTree);
29         return root;
30     }
31 }// 36 ms,待优化,去掉数组拷贝

Python

 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         if len(pre) == 0:
11             return None
12         if len(pre) == 1:
13             return TreeNode(pre[0])
14         head = TreeNode(pre[0])
15         head.left = self.reConstructBinaryTree(pre[1:tin.index(pre[0])+1], tin[:tin.index(pre[0])])
16         head.right = self.reConstructBinaryTree(pre[tin.index(pre[0])+1:], tin[tin.index(pre[0])+1:])
17         return head
posted @ 2017-09-17 16:10  HitAnyKey  阅读(199)  评论(0编辑  收藏  举报