题目
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
十分钟尝试
根据先序,中序遍历结果构建二叉树,没有接触过这类题目,学习一下思路吧。
根据先序遍历,我们能够知道根,比如先序遍历的第一个元素是root元素。然后,找出当前根在中序遍历中的位置,比如为index,那么中序遍历index左右侧分别为左子树和右子树,递归调用,完成二叉树的构建。
在递归调用的时候,左右子树分割就是我们找到的inIndex,主要当前根节点索引的变化,左子树是preStart+1,右子树是preStart+inIndex-inStart+1
/**
* 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) {
return helper(0,0,inorder.length-1,preorder,inorder);
}
private TreeNode helper(int preStart,int inStart,int inEnd,int[] preorder,int[] inorder){
if(preStart>preorder.length-1||inStart>inEnd){
return null;
}
//创建当前根,从先序遍历获取根节点
int currRoot=preorder[preStart];
TreeNode root=new TreeNode(currRoot);
int inIndex=0;
for(int i=0;i<inorder.length;i++){
if(inorder[i]==currRoot){
inIndex=i;
}
}
//左子树根节点为preStart+1,从先序遍历获得
root.left=helper(preStart+1,inStart,inIndex-1,preorder,inorder);
//右子树根节点为preStart+inIndex-inStart+1,从先序遍历获得
root.right=helper(preStart+inIndex-inStart+1,inIndex+1,inEnd,preorder,inorder);
return root;
}
}