# LeetCode 106

2020.9.26

## 我的通过代码

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
int[] in;
int[] post;
TreeNode node = null;
public TreeNode buildTree(int[] inorder, int[] postorder) {
in = inorder;
post = postorder;
node = create(0,inorder.length-1,0,postorder.length-1);
return node;

}

public TreeNode create(int beginInorder,int endInorder,int beginPostorder,int endPostorder) {
int length = endInorder - beginInorder + 1; //数组长度
if(length <= 0) return null;
TreeNode root = new TreeNode(post[endPostorder]);
int pos = getIndex(in,root.val);
root.left = create(beginInorder,pos-1,beginPostorder,beginPostorder+pos-beginInorder-1);
root.right = create(pos+1,endInorder,beginPostorder+pos-beginInorder,endPostorder-1);
return root;
}

public int getIndex(int[] arr, int val) {
for(int i=0;i<arr.length;i++) {
if(arr[i] == val) {
return i;
}
}
return -1;
}
}


/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
int[] in;
int[] post;
public TreeNode buildTree(int[] inorder, int[] postorder) {
in = inorder;
post = postorder;
TreeNode node = null;
create(0,inorder.length-1,0,postorder.length-1,node);
return node;

}

public void create(int beginInorder,int endInorder,int beginPostorder,int endPostorder,TreeNode node) {
int length = endInorder - beginInorder + 1; //数组长度
if(length <= 0) return;
node = new TreeNode(post[endPostorder]);
System.out.println(node.val);
int pos = getIndex(in,node.val);
create(beginInorder,pos-1,beginPostorder,beginPostorder+pos-beginInorder-1,node.left);
create(pos+1,endInorder,beginPostorder+pos-beginInorder,endPostorder-1,node.right);
}

public int getIndex(int[] arr, int val) {
for(int i=0;i<arr.length;i++) {
if(arr[i] == val) {
return i;
}
}
return -1;
}
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

谁用了我的ksk当昵称？

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-24

02-28 200
08-16 31
08-02 1万+
09-04 1039
09-02 487
08-01