/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
*@param preorder : A list of integers that preorder traversal of a tree
*@param inorder : A list of integers that inorder traversal of a tree
*@return : Root of a tree
*/
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0||inorder.length==0){
return null;
}
return bTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode bTree(int []preorder,int i,int j,int []inorder,int k,int l){
int index;
TreeNode root=new TreeNode(preorder[i]);
index=find(inorder,preorder[i]);
if(i==j){
return root;
}
if(index==k){
root.left=null;
}else{
root.left=bTree(preorder,i+1,i+index-k,inorder,k,index-1);
}
if(index==l){
root.right=null;
}else{
root.right=bTree(preorder,i+index-k+1,j,inorder,index+1,l);
}
return root;
}
public int find(int []arr,int k){
for(int i=0;i<arr.length;i++){
if(arr[i]==k){
return i;
}
}
return -1;
}
}
根据树的先序和中序遍历输出树(java)
最新推荐文章于 2023-01-18 20:50:58 发布