本文实例讲述了C语言实现找出二叉树中某个值的所有路径的方法,是非常常用的一个实用算法技巧。分享给大家供大家参考。
具体实现方法如下:
#include <iostream>#include <vector>#include <iterator>#include <algorithm>using namespace std;vector<int> 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<int>(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程序算法设计的学习有一定的借鉴价值。
新闻热点
疑难解答
图片精选