printing all binary trees from inorder traversal

前端 未结 2 1231
南旧
南旧 2020-12-16 02:12

Came across this question in an interview. Given inorder traversal of a binary tree. Print all the possible binary trees from it.

Initial thought:

If say we

相关标签:
2条回答
  • 2020-12-16 02:14

    I'd write one function for constructing the trees and another for printing them.

    The construction of the trees goes like this:

    #include <vector>
    #include <iostream>
    #include <boost/foreach.hpp>
    
    struct Tree {
        int value;
        Tree* left;
        Tree* right;
    
        Tree(int value, Tree* left, Tree* right) :
            value(value), left(left), right(right) {}
    };
    
    typedef std::vector<Tree*> Seq;
    
    Seq all_trees(const std::vector<int>& xs, int from, int to)
    {
        Seq result;
        if (from >= to) result.push_back(0);
        else {
            for (int i = from; i < to; i++) {
                const Seq left = all_trees(xs, from, i);
                const Seq right = all_trees(xs, i + 1, to);
                BOOST_FOREACH(Tree* tl, left) {
                    BOOST_FOREACH(Tree* tr, right) {
                        result.push_back(new Tree(xs[i], tl,  tr));
                    }
                }
            }
        }
        return result;
    }
    
    Seq all_trees(const std::vector<int>& xs)
    {
        return all_trees(xs, 0, (int)xs.size());
    }
    

    Observe that for root value there are multiple trees that be constructed from the values to the left and the right of the root value. All combinations of these left and right trees are included.

    Writing the pretty-printer is left as an exercise (a boring one), but we can test that the function indeed constructs the expected number of trees:

    int main()
    {
        const std::vector<int> xs(3, 0); // 3 values gives 5 trees.
        const Seq result = all_trees(xs);
        std::cout << "Number of trees: " << result.size() << "\n";
    }
    
    0 讨论(0)
  • 2020-12-16 02:23

    This problem breaks down quite nicely into subproblems. Given an inorder traversal, after choosing a root we know that everything before that is the left subtree and everthing after is the right subtree (either is possibly empty).

    So to enumerate all possible trees, we just try all possible values for the root and recursively solve for the left & right subtrees (the number of such trees grows quite quickly though!)

    antonakos provided code that shows how to do this, though that solution may use more memory than desirable. That could be addressed by adding more state to the recursion so it doesn't have to save lists of the answers for the left & right and combine them at the end; instead nesting these processes, and printing each tree as it is found.

    0 讨论(0)
提交回复
热议问题