题目的要求如下:
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
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
大体的要求就是给你一棵二叉树的先序遍历和中序遍历,让你构建一棵二叉树。
一.我的解法
因为给出的是先序遍历和中序遍历,所以可以先根据先序遍历确定根节点的值(即根节点的位置在先序遍历的第一个)。然后再利用已知道的根结点的值确定根节点在中序遍历中的位置,此时就可以知道中序遍历的数组中在根节点之前的都是左子树,根节点后面的都是右子树。此时利用递归,可以比较简单地完成构造。
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return construct(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode construct(int[] preorder,int prestart,int preend,int[] inorder,int instart,int inend){
if(prestart>preend||instart>inend) return null;
TreeNode root=new TreeNode(preorder[prestart]);
int posRoot=0;
for(int i=instart;i<=inend;i++)
{
if(root.val==inorder[i])
{
posRoot=i;
break;
}
}
int len=posRoot-instart;
root.left=construct(preorder,prestart+1,prestart+len,inorder,instart,posRoot-1);
root.right=construct(preorder,prestart+len+1,preend,inorder,posRoot+1,inend);
return root;
}
}
一般情况下的平衡的二叉树的时间复杂度是O(nlogn),但是如果遇到比较极端的,像左斜树那样,那么时间复杂度就会变成O(N^2)。
二.扩展
为了避免这个问题,其实最重要的就是不用遍历中序的数组去寻找根节点,而是用哈希表,因为哈希表的存取的时间都是O(1)。这样可以优化这个算法,把时间复杂度降低至O(n)。
class Solution {
Map<Integer,Integer> map=new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for(int i=0;i<inorder.length;i++)
{
map.put(inorder[i],i);
}
return construct(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode construct(int[] preorder,int prestart,int preend,int[] inorder,int instart,int inend){
if(prestart>preend||instart>inend) return null;
TreeNode root=new TreeNode(preorder[prestart]);
int posRoot=map.get(root.val);
int len=posRoot-instart;
root.left=construct(preorder,prestart+1,prestart+len,inorder,instart,posRoot-1);
root.right=construct(preorder,prestart+len+1,preend,inorder,posRoot+1,inend);
return root;
}
}
如果对这个问题想更多地了解一下,可以参考
https://articles.leetcode.com/construct-binary-tree-from-inorder-and-preorder-postorder-traversal/
如果有什么错误或可以改进的地方,请大家指出。