You are given a binary tree in which each node contains a value. design an algorithm to print all paths which sum up to that value. note that it can be any path in the tree-it does not have to start at the root.
Ideas:
Since the beginning of the path is not necessarily in the root, it is not enough to find all the paths starting from the root. Each node may start or end. If any node is used as the end node, It is pushed to the root node. If there is a sum of values in the path, it is a satisfying path, but it cannot be stopped until it is pushed to the root node, because the reverse push sequence may be 2 + 3-1 + 1. If the value is 5, 2 + 3 is satisfied, but 2 + 3-1 + 1 is also satisfied, therefore, we have to roll it down to the root to find all the paths.
Void func (node * n, int * Buf, int level, int sum) // n is the end node. Buf stores the key from this node to each root node, level is depth, sum is required and {If (n = NULL) {return;} Buf [level] = N-> key; int temp = sum; for (INT I = level; I> = 0; I --) {temp-= Buf [I]; If (temp = 0) {for (Int J = I; j <level; j ++) {printf ("% d,", Buf [J]);} printf ("% d \ n ", buf [level]) ;}} func (n-> left, Buf, level + 1, sum); func (n-> right, Buf, level + 1, sum );}
Cracking the coding interview 4.8