TikTok Interview Question: Return Postorder Traversal from Preorder and Inorder Traversals
You are given two integer arrays preorder and inorder where:
preorderis the preorder traversal of a binary tree (root → left → right).inorderis the inorder traversal of the same tree (left → root → right).
Return the postorder traversal (left → right → root) of the tree.
Example:Input:
preorder = [1,2,4,5,3,6]
inorder = [4,2,5,1,3,6]Output:
[4,5,2,6,3,1]
这道题的核心在于理解三种遍历之间的关系。前序遍历的第一个元素一定是当前子树的根节点,而中序遍历可以帮助我们确定左子树和右子树的范围。通过不断递归地拆分区间,就能模拟整棵树的结构,最终按照“左 → 右 → 根”的顺序输出后序遍历结果。关键难点在于准确划分左右子树区间。
正文完