C說話完成找出二叉樹中某個值的一切途徑的辦法。本站提示廣大學習愛好者:(C說話完成找出二叉樹中某個值的一切途徑的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C說話完成找出二叉樹中某個值的一切途徑的辦法正文
本文實例講述了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法式算法設計的進修有必定的自創價值。