给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
/**
* 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(preorder!=null && preorder.length>0 && inorder!=null && inorder.length>0 ){
int rootVal = preorder[0];
int rootIndex = getIndex(inorder,rootVal);
int[] leftInOrder = Arrays.copyOfRange(inorder,0,rootIndex);
int[] rightInOrder = Arrays.copyOfRange(inorder,rootIndex+1,inorder.length);
int[] leftPreOrder = Arrays.copyOfRange(preorder,1,leftInOrder.length+1);
int[] rightPreOrder = Arrays.copyOfRange(preorder,leftInOrder.length+1,rightInOrder.length+leftInOrder.length+1);
TreeNode leftNode = buildTree(leftPreOrder,leftInOrder);
TreeNode rightNode = buildTree(rightPreOrder,rightInOrder);
TreeNode resultNode = new TreeNode(rootVal,leftNode,rightNode);
return resultNode;
}
return null;
}
public int getIndex(int[] nums,int num){
if(nums!=null && nums.length>0){
for(int i = 0;i<nums.length;i++){
if(nums[i] == num){
return i;
}
}
}
return -1;
}
}
执行用时:
6 ms, 在所有 Java 提交中击败了14.32%的用户
内存消耗:
41.8 MB, 在所有 Java 提交中击败了6.48%的用户