原题
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:You may assume that duplicates do not exist in the tree.
原题链接:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
解题思路
前序遍历与中序遍历的结构为:
前序遍历:[ 根节点, 左子树节点X个, 右子树节点Y个 ];
中序遍历:[ 左子树节点X个, 根节点, 右子树节点Y个 ];
因此,解题思路为:1、前序遍历的第一个节点为根节点;
2、中序遍历中可找到根节点,在根节点之前的为左子树的节点,在根节点之后的为右子树的节点;
3、知道了左子树的节点个数与右子树的节点个数后,可以找到前序遍历中左子树节点与右子树节点;
4、递归终止条件为前序遍历仅有一个节点,此时该节点即为根节点。
代码1
该实现参考: https://discuss.leetcode.com/topic/3695/my-accepted-java-solution/2,比较简洁。public class Solution105_recursive {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildTreeHelper(0, 0, inorder.length - 1, preorder, inorder);
}
private TreeNode buildTreeHelper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {
if (preStart > preorder.length - 1 || inStart > inEnd)
return null;
TreeNode root = new TreeNode(preorder[preStart]);
int inIndex = 0;
for (int i = inStart; i <= inEnd; i++){
if (inorder[i] == root.val)
inIndex = i;
}
root.left = buildTreeHelper(preStart + 1, inStart, inIndex - 1, preorder, inorder);
root.right = buildTreeHelper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);
return root;
}
}
代码2
为自己最初的解法,
public class Solution105_recursive {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0)
return null;
else if (preorder.length == 1)
return new TreeNode(preorder[0]);
int rootIndexOfInorder = getIndexFromArray(preorder[0], inorder);
int[] leftInOrder = getSubArray(inorder, 0, rootIndexOfInorder - 1);
int[] rightInOrder = getSubArray(inorder, rootIndexOfInorder + 1, inorder.length - 1);
int[] leftPreOrder = getSubArray(preorder, 1, leftInOrder.length);
int[] rightPreOrder = getSubArray(preorder, leftInOrder.length + 1, leftInOrder.length + rightInOrder.length);
TreeNode root = new TreeNode(preorder[0]);
root.left = buildTree(leftPreOrder, leftInOrder);
root.right = buildTree(rightPreOrder, rightInOrder);
return root;
}
private int[] getSubArray(int[] array, int start, int end) {
if (start > end)
return new int[0];
int[] subArray = new int[end - start + 1];
int indexOfSubArray = 0, indexOfArray = start;
while (indexOfArray != end)
subArray[indexOfSubArray++] = array[indexOfArray++];
subArray[indexOfSubArray] = array[indexOfArray];
return subArray;
}
private int getIndexFromArray(int val, int[] array) {
int index = 0;
while (val != array[index++]);
return --index;
}
}