两种方法:
一、递归
有先序序列得到根节点的值,创建根节点,再递归构造左子树,右子树。 由先序得到根结点,再在中序序列找到根节点,根节点左边就是左子树,右边就是右子树。
在中序序列中找根节点,就可以用到哈希结构,这里是想得到她的坐标,所以value存坐标。
Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private Map<Integer,Integer> indexMap;
public TreeNode myBuildTree(int[] preorder,int[] inorder,int preLeft,int preRight,int inLeft,int inRight){
if(preLeft>preRight||inLeft>inRight) return null;
int pre_rootindex=preLeft;
int in_rootindex=indexMap.get(preorder[preLeft]);
TreeNode root=new TreeNode(preorder[preLeft]);
root.left=myBuildTree(preorder,inorder,preLeft+1,in_rootindex-inLeft+pre_rootindex,inLeft,in_rootindex-1);
root.right=myBuildTree(preorder,inorder,in_rootindex-inLeft+pre_rootindex+1,preRight,in_