笔试题:求二叉树和值为sum的所有路径

#include 
#include 
using namespace std;

struct  TreeNode
{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int d = int()):data(d), left(NULL), right(NULL){}
};
class Tree
{
public:
    Tree() :root(NULL){}
    void Insert(int VLR[], int LVR[],int n)
    {
        Insert(root, VLR, LVR, n);
    }
    void Printf()
    {
        Printf(root);
    }
    void PrintfSum(int sum)
    {
        stack st;
        PrintfSum(root, st,sum);
    }
private:
    void PrintfSum(TreeNode* t, stack& st,int sum)
    {
        if (t == NULL)
        {
            if (sum == 0)
            {
                stack sp = st;
                while (sp.empty() == false)
                {
                    cout << sp.top()->data << " ";
                    sp.pop();
                }
                cout << endl;
            }
            //st.pop();
            return;
        }
        else
        {
            st.push(t);
            sum -= t->data;
            PrintfSum(t->left, st,sum);
            if (t->right!=NULL)
            PrintfSum(t->right, st,sum);
            st.pop();
        }
    }
    void Insert(TreeNode *&t, int VLR[], int LVR[], int n)
    {
        if (n == 0)return;
        int i = 0;
        while (VLR[0] != LVR[i])i++;
        t = new TreeNode(VLR[0]);
        Insert(t->left, VLR + 1, LVR, i);
        Insert(t->right, VLR + i + 1, LVR + i+1, n - i - 1);
    }
    void Printf(TreeNode *t)
    {
        if (t != NULL)
        {
            cout << t->data << " ";
            Printf(t->left);
            Printf(t->right);
        }
    }
private:
    TreeNode *root;
};
int main()
{
    Tree t;
    int VLR[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    int LVR[] = {4,3,6,5,7,2,9,8,10,1,12,11,13,14,15,16};
    t.Insert(VLR,LVR,sizeof(LVR)/sizeof(int));
    t.Printf();
    cout << endl;
    t.PrintfSum(24);
    return 0;
}

你可能感兴趣的:(笔试题)