最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

如何在二叉樹中找出和為某一值的所有路徑

 更新時(shí)間:2013年05月29日 12:02:31   作者:  
本篇文章是對(duì)在二叉樹中找出和為某一值的所有路徑方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
代碼如下所示,不足之處,還望指正!
復(fù)制代碼 代碼如下:

// BinaryTree.cpp : 定義控制臺(tái)應(yīng)用程序的入口點(diǎn)。
//C++實(shí)現(xiàn)鏈?zhǔn)蕉鏄?,在二叉樹中找出和為某一值的所有路?BR>#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<<"請(qǐng)輸入根節(jié)點(diǎn):"<<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);
};
//析構(gòu)函數(shù)
template <class T>
void BiTree<T>::Release(BiNode<T> *bt)
{

 if(bt==NULL)
 {
  Release(bt->lchild );
  Release(bt->rchild );
  delete bt;
 }
}
//建立二叉樹
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<<"調(diào)用左孩子"<<endl;
     Create(bt->lchild );
     cout<<"調(diào)用右孩子"<<endl;
     Create(bt->rchild );
    }
}
//求樹的深度
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;
}

輸入一棵二叉樹,從樹的根節(jié)點(diǎn)開始往下訪問,一直到葉節(jié)點(diǎn)所經(jīng)過的所有節(jié)點(diǎn)形成一條路徑。輸出和與某個(gè)數(shù)相等的所有路徑。
例如: 二叉樹
         3
      2     6
   5    4
則和為9的,路徑有兩條,一條為3,6  另一條為3, 2, 4。 

相關(guān)文章

最新評(píng)論

云浮市| 河北省| 于都县| 永吉县| 巢湖市| 闽清县| 利辛县| 保德县| SHOW| 桃园县| 克拉玛依市| 泰和县| 汪清县| 修文县| 汝阳县| 化德县| 名山县| 云和县| 米林县| 福安市| 宝坻区| 夏津县| 华阴市| 册亨县| 博客| 江都市| 湘潭市| 陈巴尔虎旗| 中宁县| 延吉市| 邵阳市| 墨玉县| 泌阳县| 鄂伦春自治旗| 马尔康县| 江西省| 南阳市| 南木林县| 沈阳市| 含山县| 瑞安市|