2023.10.21
本题需要根据前序遍历序列和中序遍历序列来构造出一颗二叉树。类似于从中序与后序遍历序列构造二叉树 。使用递归, java代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(inorder.length == 0) return null;
int rootValue = preorder[0];
TreeNode root = new TreeNode(rootValue);
if(inorder.length == 1) return root;
//找到中序遍历的切割点
int seg = 0;
for(int i=0; i<inorder.length; i++){
if(inorder[i] == rootValue){
seg = i;
break;
}
}
int[] in_left = Arrays.copyOfRange(inorder,0,seg);
int[] in_right = Arrays.copyOfRange(inorder,seg+1,preorder.length);
preorder = Arrays.copyOfRange(preorder,1,preorder.length);//去掉第一个元素,也就是根节点的值
int[] pre_left = Arrays.copyOfRange(preorder,0,in_left.length);
int[] pre_right = Arrays.copyOfRange(preorder,in_left.length,preorder.length);
//递归处理左右子树
root.left = buildTree(pre_left,in_left);
root.right = buildTree(pre_right,in_right);
return root;
}
}