C implements the method of finding all the paths to a value in a binary tree

  • 2020-04-02 02:44:59
  • OfStack

In this paper, an example is given to illustrate the method of C language to find all the paths of a value in binary tree. Share with you for your reference.

The specific implementation method is as follows:


#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);
}

Interested friends can test run this article example. It is believed that the algorithm described in this paper has certain reference value to the learning of C program algorithm design.


Related articles: