【LeetCode】#105从前序和中序遍历序列构造二叉树(Construct Binary Tree from Preorder and Inorder Traversal)
题目描述
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
示例
给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/
9 20
/
15 7
Description
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Example
given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/
9 20
/
15 7
解法
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0)
return null;
return helper(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
}
public TreeNode helper(int[] preorder, int[] inorder, int begin1, int end1, int begin2, int end2){
if(begin1==preorder.length)
return null;
TreeNode root = new TreeNode(preorder[begin1]);
if(begin1==end1)
return root;
for(int index=end2; index>=begin2; index--){
if(preorder[begin1]==inorder[index]){
int length = index - begin2;
root.left = helper(preorder, inorder, begin1+1, begin1+length, begin2, index-1);
root.right = helper(preorder, inorder, begin1+length+1, end1, index+1, end2);
return root;
}
}
return null;
}
}