題目:輸入一個(gè)整數(shù)和一棵二元樹粥脚。從樹的根結(jié)點(diǎn)開始往下訪問(wèn)一直到葉結(jié)點(diǎn)所經(jīng)過(guò)的所有結(jié)點(diǎn)形成一條路徑理盆。打印出和與輸入整數(shù)相等的所有路徑确镊。例如 輸入整數(shù)22和如下二元樹
則打印出兩條路徑:10, 12和10, 5, 7愚臀。
struct TreeNode {
int data;
TreeNode * left;
TreeNode * right;
};
void printPaths(TreeNode * root, int sum) {
int path[MAX_HEIGHT];
helper(root, sum, path, 0);
}
void helper(TreeNode * root, int sum, int path[], int top) {
path[top++] = root.data;
sum -= root.data;
if (root->left == NULL && root->right==NULL) {
if (sum == 0) printPath(path, top);
} else {
if (root->left != NULL) helper(root->left, sum, path, top);
if (root->right!=NULL) helper(root->right, sum, path, top);
}
top --;
sum -= root.data;
}