PHP二叉树怎么寻找路径,如何在二叉树中找出和为某一值的所有路径

代码如下所示,不足之处,还望指正!

// BinaryTree.cpp : 定义控制台应用程序的入口点。

//C++实现链式二叉树,在二叉树中找出和为某一值的所有路径

#include "stdafx.h"

#include

#include

#include

using namespace std;

static int sum(0);

static int count(0);

template

struct BiNode

{

T data;

struct BiNode *rchild,*lchild;

};

template

class BiTree

{

public:

BiTree(){

cout<

Create(root);

if (NULL != root)

{

cout<data<

}

else

{

cout << "The BinaryTree is empty." << endl;

}

}

~BiTree(){Release(root);}

int Depth(){return Depth(root);}

int FindPath(T i)

{

stack*> sta;

return FindPath(i, root, sta);

};

private:

BiNode *root;

void Create(BiNode* &bt);

void Release(BiNode *bt);

int Depth(BiNode* bt);

int FindPath(T i, BiNode* bt, stack*> &sta);

};

//析构函数

template

void BiTree::Release(BiNode *bt)

{

if(bt==NULL)

{

Release(bt->lchild );

Release(bt->rchild );

delete bt;

}

}

//建立二叉树

template

void BiTree::Create(BiNode* &bt)

{

T ch;

cin>>ch;

if(ch== 0)bt=NULL;

else

{

bt=new BiNode;

bt->data =ch;

cout<

Create(bt->lchild );

cout<

Create(bt->rchild );

}

}

//求树的深度

template

int BiTree::Depth(BiNode* bt)

{

if (NULL == bt)

{

return 0;

}

int d1 = Depth(bt->lchild);

int d2 = Depth(bt->rchild);

return (d1 > d2 ? d1 : d2)+ 1;

}

template

int BiTree::FindPath(T i, BiNode* bt, stack*> &sta)

{

if (NULL != bt)

{

sta.push(bt);

}

sum += bt->data;

if (sum == i && bt->lchild == NULL && bt->rchild == NULL)

{

stack*> sta2(sta);

BiNode* 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 a;

cout << "There are " << a.FindPath(9) << " path all." << endl;

}

输入一棵二叉树,从树的根节点开始往下访问,一直到叶节点所经过的所有节点形成一条路径。输出和与某个数相等的所有路径。

例如: 二叉树         3

2     6

5    4

则和为9的,路径有两条,一条为3,6  另一条为3, 2, 4。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值