package leetcode.剑指Offer.重建二叉树;
import java.util.Arrays;
public class LeetCode {
public static void main(String[] args) {
System.out.println(new Solution().buildTree(new int[] {3, 9, 20, 15, 7}, new int[] {9, 3, 15, 20, 7}));
}
}
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null || preorder.length == 0 || preorder.length != inorder.length) {
return null;
}
TreeNode rootTreeNode = new TreeNode(preorder[0]);
if (preorder.length == 1) {
return rootTreeNode;
}
int rootValue = preorder[0];
int rootIndex = 0;
for (int i = 0; i < inorder.length; i++) {
if (inorder[i] == rootValue) {
rootIndex = i;
break;
}
}
rootTreeNode.left = buildTree(Arrays.copyOfRange(preorder, 1, rootIndex + 1), Arrays.copyOfRange(inorder, 0, rootIndex));
rootTreeNode.right = buildTree(Arrays.copyOfRange(preorder, rootIndex + 1, preorder.length), Arrays.copyOfRange(inorder, rootIndex + 1, inorder.length));
return rootTreeNode;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
image.png
网友评论