根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
//前序的第一个节点就是整个树的根节点
//在中序的数组中找到根节点,中序数组中根节点左边就是左子树,右边就是右子树,这样我们可以知道左子树节点的数量和右子树节点数量
//那么按照根节点的左右去递归构造左子树和右子树即可
//为了能快速的在中序数组中找到根节点,我们可以使用map对中序节点进行存储,查找的效率可以提高,但是同时空间变成O(n)
Map<Integer,Integer> map = new HashMap<>();
int length = inorder.length;
for (int i = 0;i < length;i++) {
map.put(inorder[i],i);
}
return build(map,preorder,inorder,0,length-1,0,length-1);
}
private TreeNode build(Map<Integer,Integer> map,int[] preorder, int[] inorder,int pl,int pr,int il,int ir) {
if (pr < pl || ir < il) {
return null;
}
//首先构建一下根节点
TreeNode root = new TreeNode(preorder[pl]);
//定位根节点在中序中的位置
int index = map.get(preorder[pl]);
//左子树个数
int leftCount = index-il;
//构建根节点的左子树和右子树
//前序的pl+1到pl+leftCount对应着中序的il到index-1
root.left = build(map,preorder,inorder,pl+1,pl+leftCount,il,index-1);
//前序的pl+leftCount+1到pr对应着中序的index+1到ir
root.right = build(map,preorder,inorder,pl+leftCount+1,pr,index+1,ir);
return root;
}
}
这个问题其实最重要的还是我们要明白二叉树的前序和中序遍历的规则,前序是按照根->左->右的方式进行遍历,中序是左->根->右的方式遍历,在了解这个了之后,我们就可以很轻松的找出二叉树的根节点,就是前序的第一个节点,找到根节点在中序中的位置了之后,我们就可以明确根节点的左子树和右子树的个数,再根据已知的信息去递归的构建左右子树并与根节点进行连接就好。