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

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

#include <iostream>
#include <assert.h>
#include "btree.h"
 
void printPath(int* path, int size)
{
    for (int i = 0; i < size; ++i)
        std::cout << path[i] << " ";
    std::cout << std::endl;
}

void findPath(const TNode* root, int sum, int path[], int top)
{
    assert(root);
    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)
		findPath(root->_left, sum, path, top);
        if (root->_right != NULL)
            findPath(root->_right, sum, path, top);
    }
    --top;
    sum += root->_data;
 }
 
void printPaths(const TNode* root, int treeHeight, int sum) 
{
    int *path = new int[treeHeight];
    findPath(root, sum, path, 0);
    delete [] path;
    path = NULL;
}
 
int main()
{
    int array[] = {15,9,17,5,11,4,6};
    int size = sizeof(array) / sizeof(array[0]);

    BTree tree;
    tree.createTree(array, size);
    int treeHeight = tree.height();
    std::cout << treeHeight << std::endl;
    printPaths(tree.root(), treeHeight, 35);  // 寻找和为35的二叉树路径

    return 0;
}
本人觉的这个算法很巧妙,不是通过加和的方式,而是减值的方式,当减为0时,即是要找的路径,并且路径通过一个数组就记录的方式也非常方便和简单!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值