我思故我在系列—数据结构题(题目来自July,整理者July,非常感谢!)

日月流转,朝夕变换,我们的生活不是那过去的好时光,不是未来的乌托邦,而是现实本身!   ——摘自  奥格。曼狄诺《羊皮卷》

 

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

例如输入整数22 和如下二元树
10
/ \
5 12
/ \
4 7
则打印出两条路径:10, 12 和10, 5, 7。  


#include <assert.h>
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;

typedef struct BTreeNode
 {
   BTreeNode* Leftchild;
   BTreeNode* Rightchild;
   int Value;
}Tnode,*Tree;

void addTree(Tree& T, int num)
{
     if(T == NULL)
               {
        T = (BTreeNode *)malloc(sizeof(Tnode));
        T->Value = num;
        T->Leftchild = NULL;
        T->Rightchild = NULL;
            return;
             }
    else if(T->Value > num)
           {
            addTree((T->Leftchild), num);
            }
    else if(T->Value < num)
          {
            addTree((T->Rightchild), num);
          }
     else
         {
        cout << "重复加入同一结点" << endl;
         }
}

void findPath(    Tree pNode, int expectedSum, vector<int>& path,int& currentSum)
{
     assert(pNode!=NULL);

     currentSum += pNode->Value;
     path.push_back(pNode->Value);

     bool isLeaf = !(pNode->Leftchild) && !(pNode->Rightchild);/*判断是否为叶子节点*/
     if(currentSum == expectedSum && isLeaf)
               {
         vector<int>::iterator iter;
         for(iter = path.begin(); iter != path.end(); iter++)
                                  {
              cout << *iter << "\t";
                                  }
         cout << endl;
              }
     if(pNode->Leftchild!=NULL)
         findPath(pNode->Leftchild, expectedSum, path, currentSum);
     if(pNode->Rightchild!=NULL)
         findPath(pNode->Rightchild, expectedSum, path, currentSum);
     currentSum -= pNode->Value;
     path.pop_back();
 }

int main()
 {
    Tree T = NULL;
    vector<int> path;
    int sum = 0;
    addTree(T, 10);
    addTree(T, 12);
    addTree(T, 5);
    addTree(T, 7);
    addTree(T, 4);
    findPath(T, 22, path, sum);
     return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值