二元查找树-- 在二元树中找到和为某一值的所有路径

//在二元树中找到和为某一值的所有路径
//从树的根节点开始往下访问一直到叶节点所经过的所有结点形成的一条路径。
//打印出荷与输入整数相等的所有路径


#include <iostream>
#include <vector>
using namespace std;

typedef  int  value_type;
class BinaryNode
{
public:
    BinaryNode *left;
    BinaryNode *right;
    value_type value;
   
    BinaryNode(int v)
    {
         left = NULL;
         right = NULL;
         value = v;
    }
};

class BinaryTree
{
public:
    BinaryTree();
    void FindPath(BinaryNode *pNode, vector<int>  path, int CurrentSum, int  ExpectSum);
    void CreateTree(BinaryNode * & pNode);
    void InOrderTraverse(BinaryNode * pNode);
    BinaryNode *root;
};


BinaryTree::BinaryTree()
{
    root = NULL;
}

void BinaryTree::CreateTree(BinaryNode* & pNode)
{
    int value;
    scanf("%d", &value);
    if (value == 0)
    {
         pNode = NULL;
    }
    else
    {
         pNode = new BinaryNode(value);
         CreateTree(pNode->left);
         CreateTree(pNode->right);
    }
}

void BinaryTree::FindPath(BinaryNode *pNode, vector<int>   path, int  CurrentSum, int  ExpectSum)
{
     if(pNode == NULL)
     {
         return;
     }
     CurrentSum += pNode->value;
     path.push_back(pNode->value);
     if(pNode->left == NULL && pNode->right == NULL)
     {
         if(CurrentSum == ExpectSum)
         {
             for(vector<int>::iterator iter = path.begin(); iter != path.end(); iter ++)
             {
                  cout << *iter <<" ";
             }
             cout << endl;
         }
         return;
     }
     FindPath(pNode->left, path, CurrentSum, ExpectSum);
     FindPath(pNode->right, path, CurrentSum, ExpectSum);

}

void BinaryTree::InOrderTraverse(BinaryNode *pNode)
{
     if (pNode == NULL)
     {
         return;
     }
     InOrderTraverse(pNode->left);
     cout << pNode->value <<" ";
     InOrderTraverse(pNode->right);
}

int main()
{
   
    vector<int> path;
    int CurrentSum;
    int ExpectSum;
    cout << "建立二叉树" << endl;
    BinaryTree tree;
    tree.CreateTree(tree.root);
    tree.InOrderTraverse(tree.root);
    cout << endl;
    
    int num = 0;
    while(scanf("%d", &ExpectSum)!=EOF)
    {
         CurrentSum = 0;
         path.clear();
         tree.FindPath(tree.root, path, CurrentSum, ExpectSum);
    }
    return 0;
}

/*

建立二叉树
10 5 2 0 0 7 0 0 15 10 0 0 20 0 0
2 5 7 10 10 15 20
17
10 5 2
22
10 5 7
35
10 15 10
45
10 15 20

*/





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值