leetcode 105. 从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder == null || preorder.length == 0) { return null; } int length = preorder.length - 1; TreeNode node = new TreeNode(preorder[ 0]); find (preorder, inorder, node, 0, length, 0, length); return node; } private void find (int[] preorder, int[] inorder, TreeNode node, int st, int end, int st2, int end2) { if (st > end) { return; } int value = preorder[st]; int split = st2; for (int j = st2 ; j <= end2; j++) { if (inorder[j] == value) { split = j; break; } } int leftLength = split - st2; if (leftLength != 0) { TreeNode l = new TreeNode(preorder[st + 1]); node.left = l; find (preorder, inorder, l, st + 1, st + leftLength, st2, split - 1); } if (split != end2) { TreeNode r = new TreeNode(preorder[st + 1 + leftLength]); node.right = r; find (preorder, inorder, r, st + 1 + leftLength, end, split + 1, end2); } }