题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
import java.util.*;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
int m = pre.length;
int n = vin.length;
if(m == 0){
return null;
}
TreeNode root = new TreeNode(pre[0]);
for(int i = 0; i < vin.length; i++){
if(vin[i] == pre[0]){
//找到根节点,将中序遍历分为左右部分
//左孩子是pre[1]到pre[i],右孩子结点是pre[i+1]到pre[m-1]
//vin的范围是,左孩子是vin[0]到vin[i-1]
//右孩子是vin[i+1]到vin[n-1]
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(vin,0,i));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,m),Arrays.copyOfRange(vin,i+1,n));
}
}
return root;
}
}
查看10道真题和解析