题目说明
给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
提示:
- 1 <= preorder.length <= 3000
- inorder.length == preorder.length
- -3000 <= preorder[i], inorder[i] <= 3000
- preorder 和 inorder 均无重复元素
- inorder 均出现在 preorder
- preorder 保证为二叉树的前序遍历序列
- inorder 保证为二叉树的中序遍历序列
示例
示例 1:

1 2
| Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7]
|
示例 2:
1 2
| Input: preorder = [-1], inorder = [-1] Output: [-1]
|
笔者理解
此题是一道二叉树算法问题,在力扣题库中被定义为中等题。
解法
当笔者阅读完此题后,发现我们只需要分治构建节点以及左右子树即可,让我们来看看具体如何实现的吧。
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) { int n = preorder.length;
TreeNode result = buildNode(0, n, 0, n, preorder, inorder);
return result; }
public TreeNode buildNode(int preLeft, int preRight, int inLeft, int inRight, int[] preorder, int[] inorder) { if (preLeft == preRight) { return null; }
int now = preorder[preLeft]; TreeNode result = new TreeNode(now);
int tick = 0; for (int i = inLeft; i < inRight; i++) { if (inorder[i] == now) { break; } tick++; }
result.left = buildNode(preLeft + 1, preLeft + tick + 1, inLeft, inLeft + tick, preorder, inorder); result.right = buildNode(preLeft + tick + 1, preRight, inLeft + tick + 1, inRight, preorder, inorder);
return result; } }
|
时间和空间效率还行,可见此解法还比较适合此题。

总结
本题是今天的一题,难度是为中等,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。