18题目:
根据前序遍历和中序遍历,求二叉树
思路:
递归思想比较容易想,主要是递归过程中的对于前序遍历和中序遍历剩余数组边界的确定
/**
* Definition for a binary tree node.
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int[] preorder;//前序遍历数组
int[] inorder;//中序遍历数组
HashMap<Integer,Integer> map;//用于寻找中序遍历中的根节点下标
public TreeNode dfs(int pl,int pr,int il,int ir){
if(pl > pr) return null;
//根节点
TreeNode root = new TreeNode(preorder[pl]);
int k = map.get(root.val);//根节点在中序遍历中的下标
//左子树
//左子树的前序遍历数组:
//pl+1好理解,k-il为根据中序数组中,根节点左边的节点就是左子树的所有节点,k-il为
//左子树的节点数目,pl+k-il为左子树节点的末尾,都是起始节点(pl)+数量(k+il)的思路
root.left = dfs(pl+1,pl+k-il,il,k-1);
//右子树
root.right = dfs(pl+k-il+1,pr,k+1,ir);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
this.inorder = inorder;
map = new HashMap<Integer,Integer>();
for(int i=0;i<inorder.length;i++)map.put(inorder[i],i);
return dfs(0,preorder.length-1,0,inorder.length-1);
}
}