找出二叉树中和为某一定值的所有路径

来源:互联网 发布:天下三捏脸数据 编辑:程序博客网 时间:2024/04/25 18:12

题目如题所示,思路如下:

用前序遍历的方式访问到某一节点时,我们把该节点添加到路径上,并累加该节点的值。

如果该节点为叶子节点且路径中节点的值刚好等于输入的定值,则当前路径符合要求,

我们把这条路径打印出来。如果当前节点不满足条件,则访问他的子结点。当前节点

访问结束之后,递归函数将自动返回到它的父亲节点。


代码如下:

#include <stdlib.h>#include <stdio.h>typedef struct BiTree{    int data;    struct BiTree *lchild;    struct BiTree *rchild;    }BiTree;BiTree* createTree(BiTree *root){    int temp;    scanf("%d",&temp);    if (temp!=-1) {        root = (BiTree*)malloc(sizeof(BiTree));        root->data = temp;        root->lchild = createTree(root->lchild);        root->rchild = createTree(root->rchild);    }    return root;}void preOrder(BiTree *root){    if (root) {        printf("%d ",root->data);        preOrder(root->lchild);        preOrder(root->rchild);    }}int getDepth(BiTree *root){    if (root==NULL) {        return 0;    }    int lDepth = getDepth(root->lchild);    int rDepth = getDepth(root->rchild);    return (lDepth>rDepth)?lDepth+1:rDepth+1;}int isLeaf(BiTree *root){    if (root) {        if (root->lchild==NULL&&root->rchild==NULL) {            return 1;        }    }    return 0;}void findPath(BiTree *root, int expSum, int *count, int stack[], int *top, int curSum){    if (root==NULL) {        return ;    }    stack[++(*top)] = root->data;        curSum += root->data;    if (curSum == expSum && isLeaf(root)) {        (*count)++;        printf("Found %d path: ",*count);                for (int i=0; i<=(*top); i++) {            printf("%d ",stack[i]);        }        printf("\n");    }        if (root->lchild) {        findPath(root->lchild, expSum, count, stack, top, curSum);    }        if (root->rchild) {        findPath(root->rchild, expSum, count, stack, top, curSum);    }        (*top)--;}int main(int argc, const char * argv[]){    //测试用例:10 5 4 -1 -1 7 -1 -1 12 -1 -1    BiTree *root = NULL;    root = createTree(root);    preOrder(root);    printf("\nThe depth is %d.\n",getDepth(root));        int expSum = 22;    int curSum = 0;    int count = 0;    int stack[50];    int top=-1;    findPath(root, expSum, &count, stack, &top, curSum);        if (count==0) {        printf("No path!\n");    }    return 1;}





0 0
原创粉丝点击