c语言二叉树找元素位置,C语言实现找出二叉树中某个值的所有路径的方法

本文实例讲述了C语言实现找出二叉树中某个值的所有路径的方法,是非常常用的一个实用算法技巧。分享给大家供大家参考。

具体实现方法如下:

#include

#include

#include

#include

using namespace std;

vector result;

struct Node {

Node(int i = 0, Node *pl = NULL, Node *pr = NULL) : data(i), left(pl), right(pr) {}

int data;

Node *left;

Node *right;

};

Node* Construct()

{

Node *node4 = new Node(7);

Node *node3 = new Node(4);

Node *node2 = new Node(12);

Node *node1 = new Node(5, node3, node4);

Node *root = new Node(10, node1, node2);

return root;

}

void print()

{

copy(result.begin(), result.end(), ostream_iterator(cout, " "));

cout << endl;

}

void PrintSum(Node *root, int sum)

{

if(root == NULL)

return;

result.push_back(root->data);

if(root->left == NULL && root->right == NULL && root->data == sum) {

print();

}

PrintSum(root->left, sum - root->data);

PrintSum(root->right, sum - root->data);

result.pop_back();

}

void main()

{

Node *root = Construct();

PrintSum(root, 22);

}

感兴趣的朋友可以测试运行一下本文实例。相信本文所述算法对大家C程序算法设计的学习有一定的借鉴价值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值