二叉樹中找出和爲某一值的所有路徑

在二叉樹中找出和爲某一值的所有路徑

#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時,即是要找的路徑,並且路徑通過一個數組就記錄的方式也非常方便和簡單!
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章