题目: 输入一棵二叉树和一整数,打印出二叉树节点中和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成的一条路径。
思路:使用前序遍历二叉树,将访问到的节点放入栈中,并累加栈中路径的权值,如果栈顶为页节点并且和为输入的整数,则打印该路径。若果不是页节点,则继续访问子节点。当前节点访问结束后,函数自动递归回到父节点,此时,因在函数退出之前要在已入栈的路径上删除当前节点并减去该节点的权值,以确保返回父节点时路径刚好是从根节点到父节点。
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
#define STACK_SIZE 1024
typedef struct stack {
int base;
int top;
BinaryTreeNode *data[STACK_SIZE]; // 暂不考虑溢出情况
}my_stack;
BinaryTreeNode *stack_top(my_stack *stack) {
BinaryTreeNode *val = stack->data[stack->top];
return val;
}
void stack_push(my_stack *stack, BinaryTreeNode *pTreeRoot) {
stack->data[stack->top] = pTreeRoot;
stack->top++;
}
BinaryTreeNode *stack_pop(my_stack *stack) {
stack->top--;
BinaryTreeNode *val = stack->data[stack->top];
return val;
}
int stack_size(my_stack *stack) {
int size = stack->top - stack->base;
return size;
}
void print_stack(my_stack *stack) {
printf("a line is :\n");
int i = 0;
for (i = 0; i < stack->top; i++) {
printf(" %d ", stack->data[i]->m_nValue);
}
printf("\n");
}
my_stack *path_tree_stack; // need init
void findpath(BinaryTreeNode *pTreeRoot, int expectedsum, my_stack *stack, int sum) {
sum += pTreeRoot->m_nValue;
stack_push(stack, pTreeRoot); // 先访问根节点
// 如果该节点是页节点
bool isLeaf = (pTreeRoot->m_pLeft == NULL) && (pTreeRoot->m_pRight == NULL);
if (true == isLeaf) {
print_stack(stack); // 遍历打印栈
}
// 不是页节点则继续遍历子节点
if (NULL != pTreeRoot->m_pLeft) {
findpath(pTreeRoot->m_pLeft, expectedsum, stack, sum);
}
if (NULL != pTreeRoot->m_pRight) {
findpath(pTreeRoot->m_pRight, expectedsum, stack, sum);
}
// 在返回父节点前,删除当前节点
stack_pop(stack);
}
void find_path(BinaryTreeNode *pTreeRoot, int num) {
if (NULL == pTreeRoot) {
return;
}
int sum = 0;
findpath(pTreeRoot, num, path_tree_stack, sum);
}