[Algorithm question] print the elements in the binary search tree and all paths equal to the specified number.

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.