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

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

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

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

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

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


代码如下:

#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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值