Construct Binary Tree from Inorder and Postorder Traversal
You get two traversals of the same binary tree with distinct values: inorder (left subtree, node, right subtree) and postorder (left subtree, right subtree, node). Rebuild the tree. Our traversals: inorder [9, 8, 4, 7, 2, 5], postorder [8, 9, 7, 5, 2, 4] — the tree, level by level, is [4, 9, 2, none, 8, 7, 5].
- input
inorderandpostorder: the inorder (left, root, right) and postorder (left, right, root) traversals of one binary tree whose values are all different.- returns
- The root of that tree: there is only one, since the values are all different.
- constraints
- 1 ≤ inorder.length ≤ 3000
- postorder.length = inorder.length
- −3000 ≤ inorder[i], postorder[i] ≤ 3000
- the values of inorder are all different
- inorder and postorder are traversals of the same tree
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
function buildTree(inorder, postorder) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more divide and conquer problems
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.