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

#include <iostream>
#include <stack>
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<TreeNode*> st;
        PrintfSum(root, st,sum);
    }
private:
    void PrintfSum(TreeNode* t, stack<TreeNode*>& st,int sum)
    {
        if (t == NULL)
        {
            if (sum == 0)
            {
                stack<TreeNode *> 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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值