原题链接:105. Construct Binary Tree from Preorder and Inorder Traversal
相关文章:106. Construct Binary Tree from Inorder and Postorder Traversal | Java最短代码实现
欢迎优化!
【思路】
本题考查前序遍历和中序遍历来构造二叉树。我们知道前序遍历的第一个节点存储的是根节点,在中序遍历中找到该节点,将中序遍历划分为前半部分的左子树中序遍历和后半部分的右子树中序遍历,如此递归:
public TreeNode buildTree(int[] preorder, int[] inorder) {
return createTree(preorder, 0, inorder, 0, preorder.length - 1);
}
private TreeNode createTree(int[] preorder, int preIndex, int[] inorder, int inBeg, int inEnd) {
if (preIndex >= preorder.length) return null;
int findIndex = 0;
for (int i = inBeg; i <= inEnd; i++)
if (preorder[preIndex] == inorder[i]) {
findIndex = i;
break;
}
TreeNode root = new TreeNode(preorder[preIndex]);
if (findIndex > inBeg)
root.left = createTree(preorder, preIndex + 1, inorder, inBeg, findIndex - 1);
if (findIndex < inEnd)
root.right = createTree(preorder, preIndex + 1 + findIndex - inBeg, inorder, findIndex + 1, inEnd);
return root;
}
202 / 202
test cases passed. Runtime: 21 ms Your runtime beats 21.67% of javasubmissions.
欢迎优化!