【原创】leetCodeOj ---Construct Binary Tree from Preorder and Inorder Traversal 解题报告

时间:2022-07-28 16:14:53

原题地址:

https://oj.leetcode.com/problems/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.

方法:

非常单纯的递归应用。当然首先你需要知道什么叫前序遍历,什么叫中序遍历。我们可以通过前序和中序遍历来构造一棵树,这个过程是递归的。

首先,我们拿到了两个序列。

其次,我们根据前序遍历序列,获得了树根,new一个树根。

然后,我们找到树根在中序遍历的位置,然后就知道左右子树的范围了。

最后,递归处理左右子树

PS:利用后序遍历和中序遍历来构造一棵树也是一样道理,关键有两点,一是找根,而是确定子树范围。

全部代码:

/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0)
return null;
return trueStuff(preorder,0,preorder.length - 1,inorder,0,inorder.length - 1);
}
private TreeNode trueStuff(int[] pre,int startp,int finp,int[] in,int starti,int fini)
{
if (startp == finp)
return new TreeNode(pre[startp]);
if (startp > finp)
return null;
TreeNode tmp = new TreeNode(pre[startp]);
int pos = findIndex(in,starti,fini,pre[startp]);
if (pos == -1)
return null;
tmp.left = trueStuff(pre,startp + 1,startp + pos - starti,in,starti,pos - 1);
tmp.right = trueStuff(pre,startp + pos - starti + 1,finp,in,pos + 1,fini);
return tmp;
}
private int findIndex(int[] in,int start,int fin,int target)
{
for (int i = start;i <= fin;i++)
if (in[i] == target)
return i;
return -1;
}
}