数据结构:题目(2)在二元树中找出和为某一值的所有路径(树)

来源:互联网 发布:appstore安装不了软件 编辑:程序博客网 时间:2024/06/05 02:48

问题描述:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。

例如输入整数22和如下二元树

  10  
  / /   
 5  12   
 /   /   
4     7
则打印出两条路径:10, 12和10, 5, 7。

思路:递归的思想。很多树的题目都是用递归解决的,例如把二元查找树转变成排序的双向链表(树)。递归的终止条件为当前为空结点或当前结点的值大于剩余和。如果当前结点的值等于剩余和,并且是叶结点,那么打印路径。否则,将剩余和减去当前结点的值,递归求解。至于路径的记录,可以利用栈的思想来实现。


#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 addBSTreeNode(BSTreeNode *&pCurrent,int value)//在这个函数中会要改变指针值,一定要记得使用引用传递{    if (pCurrent==NULL)    {        BSTreeNode* pBSTree=new BSTreeNode();        pBSTree->m_nValue=value;        pBSTree->m_pLeft=NULL;        pBSTree->m_pRight=NULL;        pCurrent=pBSTree;    }    else if (pCurrent->m_nValue<value)    {        addBSTreeNode(pCurrent->m_pRight,value);    }    else if (pCurrent->m_nValue>value)    {        addBSTreeNode(pCurrent->m_pLeft,value);    }    else    {        cout<<"node repeated"<<endl;    } }void FindPath(BSTreeNode *pNode,int sum,vector<int> &path)  {      //结点为空或值大于当前和      if(pNode == NULL || pNode->m_nValue > sum)          return;      path.push_back(pNode->m_nValue);      //判断是不是叶结点      bool isLeaf = (pNode->m_pLeft == NULL && pNode->m_pRight == NULL)? true: false; ////将所有的路径输出//if(isLeaf)  //    {  //        vector<int>::iterator iter = path.begin(); //        for(; iter != path.end(); iter++)  //            cout<<*iter<<' ';  //        cout<<endl;  //    }      //找到一条路径,打印      if(pNode->m_nValue == sum && isLeaf)      {          vector<int>::iterator iter = path.begin();  //将合适的路径输出        for(; iter != path.end(); iter++)              cout<<*iter<<' ';          cout<<endl;      }      else      {          //求剩余和          sum = sum - pNode->m_nValue;           //递归求解          FindPath(pNode->m_pLeft, sum, path);           FindPath(pNode->m_pRight, sum, path);      }      path.pop_back();//寻找要将找下一条路径,将原路径中多余部分出栈}  int main(){    BSTreeNode *pRoot=NULL;vector<int> v;    addBSTreeNode(pRoot,10);    addBSTreeNode(pRoot,5);    addBSTreeNode(pRoot,12);    addBSTreeNode(pRoot,4);    addBSTreeNode(pRoot,7);FindPath(pRoot,22,v);//最后vector是空if(v.empty())cout<<"empty vector."<<endl;    return 0;}

0 0