剑指 Offer 07. 重建二叉树
题目:输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
解法:分治思想
思路:因为前序遍历和中序遍历的数组可以表示一棵树,通过分别给定左子树和右子树前序遍历、中序遍历的数组范围,就可以建立左子树和右子树。只要我们在中序遍历中定位到根节点,那么我们就可以分别知道左子树和右子树中的节点数目。
代码:
/**
-
Definition for a binary tree node.
-
public class TreeNode {
-
int val; -
TreeNode left; -
TreeNode right; -
TreeNode(int x) { val = x; } -
}
*/
class Solution {
private static Map<Integer,Integer> map;
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0){
return null;
}
//初始化根结点
map = new HashMap<Integer,Integer>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i],i);
}
return recur(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}public TreeNode recur(int[] preorder,int[] inorder,int preStart,int preEnd,int inStart,int inEnd){
if(preStart>preEnd){
return null;
}
int roorVal = preorder[preStart];
int rootIndex = map.get(roorVal); //使用Arrays.binarysearch会出现负数
TreeNode root = new TreeNode(roorVal);
int leftTreeSize = rootIndex - inStart;
root.left = recur(preorder,inorder,preStart+1,preStart+leftTreeSize,inStart,rootIndex-1);
root.right = recur(preorder,inorder,preStart+leftTreeSize+1,preEnd,rootIndex+1,inEnd);
return root;
}
}
分析:时间复杂度和空间复杂度均为O(n)

浙公网安备 33010602011771号