/**
* 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) {
int n = preorder.length;
int preOrderLeft = 0;
int preOrderRight = n - 1;
int inOrderLeft = 0;
int inOrderRight = n - 1;
TreeNode ans = helper(preorder, preOrderLeft, preOrderRight, inorder, inOrderLeft, inOrderRight);
return ans;
}
public TreeNode helper(int[] preOrder, int preOrderLeft, int preOrderRight, int[] inOrder, int inOrderLeft, int inOrderRight) {
if (preOrderLeft > preOrderRight) {
return null;
}
int rootVal = preOrder[preOrderLeft];
int inOrderRootIndex = 0;
for (int i = 0; i < inOrder.length; i++) {
if (rootVal == inOrder[i]) {
inOrderRootIndex = i;
break;
}
}
int leftSubTreeLength = inOrderRootIndex - inOrderLeft;
TreeNode root = new TreeNode(rootVal);
root.left = helper(preOrder, preOrderLeft + 1, preOrderLeft + leftSubTreeLength, inOrder, inOrderLeft, inOrderRootIndex - 1);
root.right = helper(preOrder, preOrderLeft + leftSubTreeLength + 1, preOrderRight, inOrder, inOrderRootIndex + 1, inOrderRight);
return root;
}
}
评论