How do I find all paths in a binary tree where the sum is a value

  • 2020-04-02 00:58:08
  • OfStack

Code as shown below, shortcomings, also hope to correct!

//Binarytree.cpp: defines the entry point for the console application.
//C++ to achieve the chain binary tree, in the binary tree to find and for a value of all the paths
#include "stdafx.h"
#include<iostream>
#include<string>
#include <stack>
using namespace std;
static int sum(0);
static int count(0);
template<class T>
struct BiNode
{
 T data;
 struct BiNode<T> *rchild,*lchild;
};
template<class T>
class BiTree
{
public:
 BiTree(){
  cout<<" Please enter the root node :"<<endl;
  Create(root);
  if (NULL != root)
  {
   cout<<"root="<<root->data<<endl;
  }
  else
  {
   cout << "The BinaryTree is empty." << endl;
  }
 }
 ~BiTree(){Release(root);}
 int Depth(){return Depth(root);}
 int FindPath(T i)
 {
  stack<BiNode<T>*> sta;
  return FindPath(i, root, sta);
 };
private:
 BiNode<T> *root;
 void Create(BiNode<T>* &bt);
 void Release(BiNode<T> *bt);
 int Depth(BiNode<T>* bt);
 int FindPath(T i, BiNode<T>* bt, stack<BiNode<T>*> &sta);
};
//The destructor
template <class T>
void BiTree<T>::Release(BiNode<T> *bt) 
{

 if(bt==NULL)
 {
  Release(bt->lchild );
  Release(bt->rchild );
  delete bt;
 }
}
//Set up a binary tree
template <class T>
void BiTree<T>::Create(BiNode<T>* &bt) 
{
 T ch;
    cin>>ch;
    if(ch== 0)bt=NULL;
    else
    {
     bt=new BiNode<T>;
     bt->data =ch;
     cout<<" Call left child "<<endl;
     Create(bt->lchild );
     cout<<" Call the right child "<<endl;
     Create(bt->rchild );
    }
}
//Find the depth of the tree
template <class T>
int BiTree<T>::Depth(BiNode<T>* bt)
{
 if (NULL == bt)
 {
  return 0;
 }
 int d1 = Depth(bt->lchild);
 int d2 = Depth(bt->rchild);
 return (d1 > d2 ? d1 : d2)+ 1;
}
template <class T>
int BiTree<T>::FindPath(T i, BiNode<T>* bt, stack<BiNode<T>*> &sta)
{
 if (NULL != bt)
 {
  sta.push(bt);
 }
 sum += bt->data;
 if (sum == i && bt->lchild == NULL && bt->rchild == NULL)
 {
  stack<BiNode<T>*> sta2(sta);
  BiNode<T>* p;
  cout << "One of the path is: " ;
  while (!sta2.empty())
  {
   p = sta2.top();
   cout << p->data << " ";
   sta2.pop();
  }
  cout << endl;
  count ++;
 }
 if (NULL != bt->lchild)
 {
  FindPath(i, bt->lchild, sta);
 }
 if (NULL != bt->rchild)
 {
  FindPath(i,bt->rchild, sta);
 }
 sum -= bt->data;
 sta.pop(); 
 return count;
}
void main()
{ 
    BiTree<int> a;
   cout << "There are " << a.FindPath(9) << " path all." << endl;
}

Enter a binary tree, starting at the root of the tree and going down until all the nodes through which the leaf passes form a path. Output and all paths equal to a certain number.
For example: binary tree
                3
          2         6
    5       4
So if the sum is 9, there are two paths, one is 3,6   The other one is 3, 2, 4.  

Related articles: