Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
1 | preorder = [3,9,20,15,7] |
Return the following binary tree:
1 | 3 |
思路:这道题就需要模拟人去解决通过前序和中序遍历结果来重建二叉树的算法,用递归即可,前序遍历的第一个数字是根节点,靠这个在中序序列里找到根节点,将中序遍历中的结果分成左右子树两部分,然后分别递归去生成结点即可。通过了201/203个测试用例,剩下两个巨大的测试用例没通过没找到原因,: (。
代码如下:
1 | /** |
利用ArrayList的sublist方法时需要考虑下标的溢出问题,容易出错,我们可以给辅助函数多传几个参数,帮助提升辅助函数的作用以及使代码更加简化,数组越界的情况就比较好控制了,代码如下:
1 | /** |