题目描述:
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
中文理解:
给定二叉树的前序和中序序列,重建二叉树。
解题思路:
根据前序序列第一个元素为根节点,然后在中序序列中定位到根节点的位置,由此可以分出左右子树的前序、中旬序列,然后递归进行重建二叉树。
代码(java):
/**
* 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) {
TreeNode root=null;
if(preorder.length==0 || preorder.length!=inorder.length)return root;
root=new TreeNode(preorder[0]);
int i=0;
for(;i<inorder.length;i++){
if(preorder[0]==inorder[i])break;
}
root.left=buildTree(Arrays.copyOfRange(preorder,1,i+1),Arrays.copyOfRange(inorder,0,i));
root.right=buildTree(Arrays.copyOfRange(preorder,i+1,preorder.length),Arrays.copyOfRange(inorder,i+1,inorder.length));
return root;
}
}