Requirements needed to construct a unique BT

Pattern: Construction from traversals

medium

Two traversals pin down a binary tree with distinct values only when one of them is inorder and the other is preorder or postorder. Preorder with postorder is ambiguous whenever a node has a single child, and two copies of the same traversal add nothing.

The problem

Traversals are numbered 1 = preorder, 2 = inorder, 3 = postorder. Given two of them, a and b, return whether they always determine a unique binary tree. (1, 2) is true; (1, 3) is false.

Think first

  • What does preorder tell you that inorder does not?
  • What does inorder tell you that the others do not?
  • Can preorder and postorder tell a left child from a right child?

Hints

    Brute force, and why it fails

    Try every small tree and check whether two different ones share both traversals. The tests do exactly that with 3 values.

    The key insight

    Inorder is the only traversal that separates the left side from the right, and the others supply the roots, so exactly the pairs with inorder and one other work.

    Dry run

    answertrue

    a = 1 (preorder), b = 2 (inorder): preorder gives each root, inorder splits left and right. True.

    Step 1 of 3

    The plan

    return a != b and (a == 2 or b == 2)
    

    Complexity

    Time
    O(1)
    Space
    O(1)

    A single test.

    Edge cases

    • The same number twice.
    • Either order of the pair.
    • Values must be distinct for any of this to hold.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean uniqueBinaryTree(int a, int b) {   // 1 = preorder, 2 = inorder, 3 = postorder
            return a != b && (a == 2 || b == 2);          // inorder plus one other; two of the same tell you nothing new
        }
    }

    C++

    class Solution {
    public:
        bool uniqueBinaryTree(int a, int b) {             // 1 = preorder, 2 = inorder, 3 = postorder
            return a != b && (a == 2 || b == 2);          // inorder plus one other; two of the same tell you nothing new
        }
    };

    Python

    class Solution:
        def uniqueBinaryTree(self, a: int, b: int) -> bool:   # 1 = preorder, 2 = inorder, 3 = postorder
            return a != b and 2 in (a, b)           # inorder plus one other; two of the same tell you nothing new

    Common mistakes

    • Saying preorder and postorder are enough.
    • Forgetting the case a == b.

    Similar problems