# 重建二叉树

/**
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
/**
* 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) {
if (preorder==null||preorder.length==0) {
return null;
}
TreeNode node = construct(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
return node;
}
public TreeNode construct(int[] preOrder, int prestart, int preend, int[] inOrder, int instart, int inend){
if(prestart>preend) {
return null;
}
TreeNode node = new TreeNode(preOrder[prestart]);
//左子树长度
int leftLength = leftLengthInOrder(instart, inend, node.val, inOrder);
if(leftLength>0) {
node.left = construct(preOrder, prestart+1, prestart+leftLength, inOrder, instart, instart+leftLength-1);
}
//判断需不需要递归右子树
if(leftLength<preend-prestart) {
node.right = construct(preOrder, prestart+leftLength+1, preend, inOrder, instart+leftLength+1, inend);
}
return node;
}

public int leftLengthInOrder(int instart, int inend, int value, int[] inOrder){
int length = 0;
for(int i=instart;i<=inend&&inOrder[i]!=value;i++){
length++;
}
return length;
}
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

xiaomagezuishuai

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

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

点赞Mark关注该博主, 随时了解TA的最新博文
06-01 5480

09-20
12-15 111
01-05 343
11-22 7249