[leetCode]105. 从前序与中序遍历序列构造二叉树
csdn:https://blog.csdn.net/renweiyi1487/article/details/109327396
题目
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
解法
思路与[leetCode]106. 从中序与后序遍历序列构造二叉树一样,直接给出代码:
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0 || inorder.length == 0) return null;
return traversal(
preorder, 0, preorder.length,
inorder, 0, inorder.length
);
}
private TreeNode traversal(
int[] preorder, int preorderBegin, int preorderEnd,
int[] inorder, int inorderBegin, int inorderEnd
) {
// 1. 数组为空直接返回null
if (inorderEnd - inorderBegin == 0) return null;
// 2.根据前序遍历确定节点
int rootValue = preorder[preorderBegin];
TreeNode root = new TreeNode(rootValue);
// 如果是叶子节点则直接返回
if (inorderEnd - inorderBegin == 1) return root;
// 3.查找分割点
int delimiterIndex;
for (delimiterIndex = inorderBegin; delimiterIndex < inorderEnd; delimiterIndex++) {
if (inorder[delimiterIndex] == rootValue) break;
}
// 4.切割中序遍历
int leftInorderBegin = inorderBegin;
int leftInorderEnd = delimiterIndex;
int rightInorderBegin = delimiterIndex + 1;
int rightInorderEnd = inorderEnd;
// 5.切割前序遍历
int leftPreorderBegin = preorderBegin + 1;
int leftPreorderEnd = leftPreorderBegin + delimiterIndex - inorderBegin;
int rightPreorderBegin = leftPreorderBegin + delimiterIndex - inorderBegin;
int rightPreorderEnd = preorderEnd;
// 6. 递归
root.left = traversal(
preorder,leftPreorderBegin, leftPreorderEnd,
inorder, leftInorderBegin, leftInorderEnd
);
root.right = traversal(
preorder, rightPreorderBegin, rightPreorderEnd,
inorder, rightInorderBegin, rightInorderEnd
);
return root;
}
}