微软100题--004

//1 在二元树中找出和为某一值的所有路径

#include<iostream>
#include<vector>
using namespace std;
struct BSTreeNode
{
    int m_nValue; // value of node
    BSTreeNode *m_pLeft; // left child of node
    BSTreeNode *m_pRight; // right child of node
};
void addTree(BSTreeNode*&root,int value)
{
    if (NULL == root)
    {
        BSTreeNode *tmp = new BSTreeNode();
        tmp->m_nValue = value;
        tmp->m_pLeft = NULL;
        tmp->m_pRight = NULL;
        root = tmp;
    }
    if (root->m_nValue > value)
        return addTree(root->m_pLeft, value);
    if (root->m_nValue < value)
        return addTree(root->m_pRight, value);
}
void findPath(BSTreeNode*root, int sum, vector<int>&path, int &current)
{
    if (NULL == root)
        return;
    current += root->m_nValue;
    path.push_back(root->m_nValue);
    bool flage = ((!root->m_pLeft) && (!root->m_pRight));
    if (flage&&current == sum)
    {
        vector<int>::iterator itr = path.begin();
        for (; itr != path.end(); ++itr)
            cout << *itr << " ";
        cout << endl;
    }
    if (root->m_pLeft)
      findPath(root->m_pLeft, sum, path, current);
    if (root->m_pRight)
      findPath(root->m_pRight, sum, path, current);
    current -= root->m_nValue;
    path.pop_back();
}
void inorder(BSTreeNode*root)
{
    if (root == NULL)
        return ;
    cout << root->m_nValue << " ";
    inorder(root->m_pLeft);
    inorder(root->m_pRight);

}
int main()
{
    BSTreeNode *root = NULL;
    addTree(root, 10);
    addTree(root, 12);
    addTree(root, 5);
    addTree(root, 7);
    addTree(root, 4);
    inorder(root);
    cout << endl;
    vector<int>path;
    int sum;
    int count = 0;
    findPath(root, 22, path, count);
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值