4.8-找出二叉树和为sum的路径(始末点不一定是跟和叶)

You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.

按层遍历,然后每次从当前层往上走,如果发现和=sum,则输出该路径。

时间复杂度O(nlgn),空间复杂度O(nlgn)

#include <iostream>
#include <vector>
using namespace std;
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode *createTree(int *num, int left, int right)
{
    if (left > right)
        return NULL;

    int mid = (left + right) / 2;
    TreeNode *node = new TreeNode(num[mid]);
    node->left = createTree(num, left, mid - 1);
    node->right = createTree(num, mid + 1, right);
    return node;
}
TreeNode *sortedArrayToBST(int *num, int size)
{
    createTree(num, 0, size - 1);
}
//=====================================
void findSum(TreeNode *head, int sum, vector<int> buffer, int level)
{
    if (head == NULL)
        return;

    int tmp = sum;
    buffer.push_back(head->val);
    for (int i = level; i >= 0; i--)
    {
        tmp -= buffer[i];
        if(tmp == 0)
        {
            for (int j = i; j <= level; j++)
                cout << buffer[j] << "  ";
            cout << endl;
        }
    }

    findSum(head->left, sum, buffer, level + 1);
    findSum(head->right, sum, buffer, level + 1);
}
int main()
{
    int num[]= {1,2,3,4,5,6,7,8,9};
    TreeNode *head = sortedArrayToBST(num,9);
    vector<int> v;
    findSum(head, 5, v, 0);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值