Leecode no.105 从前序与中序遍历序列构造二叉树

package tree;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
*
* 根据一棵树的前序遍历与中序遍历构造二叉树。
*
* 注意:
* 你可以假设树中没有重复的元素。
*
* 前序遍历 preorder = [3,9,20,15,7]
* 中序遍历 inorder = [9,3,15,20,7]
*
* @author Tang
*/
public class BuildTree {

/**
* 每一次递归:
* 返回值就是当前节点node,构造出当前节点node的左节点 右节点
* 根据前序遍历结果集的第一个值,确定当前节点node的值.
* 根据该值 在中序遍历结果集中找到对应位置index,
* index左边大小(countLeft)就是node的左节点个数,index右边大小(countRight)就是根节点右节点个数
* 将preorder[] inorder[]根据节点个数截断,分别递归去确定root的左右节点
*
* @param preorder 前序遍历结果 根 左 右
* @param inorder 中序遍历结果 左 根 右
* @return
*/
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0 || inorder.length == 0){
return null;
}
if(preorder.length == 1){
return new TreeNode(preorder[0]);
}
int value = preorder[0];
TreeNode node = new TreeNode(value);

int index = 0;
for (int i = 0; i < inorder.length; i++) {
if(inorder[i] == value){
index = i;
}
}
//左节点个数
int countLeft = index;
//右节点个数
int countRight = inorder.length - 1 - index;

//判断左节点还有没有
if(countLeft > 0){
int[] newPre = Arrays.copyOfRange(preorder, 1, countLeft + 1);
int[] newIn = Arrays.copyOfRange(inorder, 0, countLeft);
node.left = buildTree(newPre, newIn);
}
if(countRight > 0){
int[] newPre = Arrays.copyOfRange(preorder, inorder.length - countRight, inorder.length);
int[] newIn = Arrays.copyOfRange(inorder, index + 1, inorder.length);
node.right = buildTree(newPre, newIn);
}

return node;
}


public static void main(String[] args) {

int[] preorder = {0,3,1,2};
int[] inorder = {3,0,2,1};

new BuildTree().buildTree(preorder, inorder);

}



}
posted @ 2021-07-09 16:42  六小扛把子  阅读(33)  评论(0编辑  收藏  举报