/**
* 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 build(preorder,inorder,0,0,inorder.length-1);
}
public TreeNode build (int[] preorder, int[] inorder, int preL,int inl,int inr){
if(inl>inr)return null;
int k=0;
for(int i=0;i<inorder.length;i++){
if(preorder[preL]==inorder[i]){
k=i;
break;
}
}
TreeNode root=new TreeNode(inorder[k]);
int leftNum=k-inl;
root.left=build(preorder,inorder,preL+1,inl,k-1);
root.right=build(preorder,inorder,preL+leftNum+1,k+1,inr);
return root;
}
}
[leetcode]105. Construct Binary Tree from Preorder and Inorder Traversal
猜你喜欢
转载自blog.csdn.net/weixin_36869329/article/details/89432364
今日推荐
周排行