Question: enter an integer and a binary tree. Access from the root node of the tree to all the nodes that the leaf node passes through to form a path. Print all paths equal to the input integer.
For example, enter the integer 24 and the following binary tree.
10
/\
6 14
/\
4 8
The following two paths are printed: 10, 14, 10, 6, and 8.
# Include <iostream> using namespace STD; # define max_len 20 typedef struct node {node (): V (0), left (null), right (null) {} node (INT _ v, node * l = NULL, node * r = NULL): V (_ v), left (L), right (r) {} int V; node * left; node * right;} snode; // lb_c: recursive and backtracking methods are used, note that the ARR parameter is an array reference (each recursion uses the same Array and is not allocated multiple times) void checksum (snode * cur, int sum, INT (& ARR) [max_len], int idx) {sum-= cur-> V; arr [idx ++] = cur-> V; // lb_c: both left and right are null., That is, if (null = cur-> left) & (null = cur-> right) {// lb_c: if the current node to be searched is 0, the path to the current node is the desired path, and the value of the nodes in this path is recorded in arr if (0 = sum) {for (INT I = 0; I <idx; I ++) {cout <arr [I] <"" ;}cout <Endl;} return ;} else {checksum (cur-> left, sum, arr, idx); checksum (cur-> right, sum, arr, idx);} // lb_c: The key here is, the subtree of the current node has been traversed. here we need to "Restore" to the traversal before backtracking! Sum + = cur-> V; -- idx;} int main () {// create BST snode N1 (4); snode N2 (8); snode N3 (6, & N1, & N2); snode N4 (14); snode root (10, & N3, & n4); // call checksum () int res [max_len]; checksum (& root, 24, res, 0); Return 0 ;}